Last time I research in Google for memory leaks, cycle reference and how garbage collection works. But all is little confusing. I understant that garbage collection works in this way:
var a = {}; // a is only reference to this object
a = 5 /* now variable a is reference to "number" (other js object)
and now the first empty object has no reference,
so it is cleaned from the memory. */
That look pretty cool. But I see have a JScript objects and COM objects in IE. If there is a circular reference between objects in COM and JScript there are memory leaks (uncleaned memory). So now I'm comfused and makes some simple examples to show what I understand, or not:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div style="width: 30px;" id='myDiv'></div>
<script language='javascript'>
"use strict";
var a = 4,
i,
div = document.createElement('div');
//no leaks
function noLeaks(b) {
this.a = a;
a = this.b;
}
var obj = new noLeaks(5);
//leak pattern
function makeLeaks(func) {
div.badAttachToCOMObject = func; // the problem is here
}
makeLeaks(function(){}); //attach reference to JScript objcet/function?
//no leaks
function size() {
return '30px'; //just a value
}
function noStyleLeaks() {
div.style.width = size();
/* DOM (COM in IE) element just get a value,
not a reference, only if I put a object or
function to the value is a problem? */
}
noStyleLeaks();
//leaks or not
function styleLeaks() {
div.style.width = document.getElementById('myDiv').style.width;/* this
is cycle reference, but maybe only between COM and COM objects?
And do not make leaks? */
}
styleLeaks();
</script>
</body>
</html>
Do I understand the main idea, or not? And one last question, Chrome has a task manager, that and windows task manager shows memory usage jump with ~1mb on every refresh when I use this from http://www.javascriptkit.com/javatutors/closuresleak/index.shtml:
function LeakMemory(){
for(i = 0; i < 50000; i++){
var parentDiv =
document.createElement("div");
}
}
Chrome(21) make leaks? I think that is not normal. So I'm more and more confused in how JS garbage collection works.