上次我在谷歌研究内存泄漏,循环引用以及垃圾收集的工作原理。但一切都有点混乱。我明白垃圾收集工作方式是这样的:
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. */
看起来很酷。 但我看到在IE中有一个JScript对象和COM对象。如果COM和JScript中的对象之间存在循环引用,则存在内存泄漏(未清除的内存)。 所以现在我已经融入并做了一些简单的例子来展示我理解或不理解:
<!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>
我是否了解主要想法?还有最后一个问题,Chrome有一个任务管理器,当我使用http://www.javascriptkit.com/javatutors/closuresleak/index.shtml时,每次刷新时,Windows任务管理器显示内存使用量跳跃大约1mb:
function LeakMemory(){
for(i = 0; i < 50000; i++){
var parentDiv =
document.createElement("div");
}
}
Chrome(21)泄漏?我认为这不正常。所以我对JS垃圾收集的工作方式越来越困惑。