循环添加/删除DOM节点会导致JavaScript中的内存泄漏? [英] Cyclic adding/removing of DOM nodes causes memory leaks in JavaScript?
问题描述
我试图用DOM元素显示动态变化的数据(添加/删除它们)。我发现几乎所有浏览器都有一个非常奇怪的行为:在我删除了一个DOM元素,然后添加一个新的浏览器后,浏览器并没有释放被删除的DOM项所占用的内存。看下面的代码来了解我的意思。在我们运行此页面之后,它将逐步进入150 MB内存。任何人都可以解释我这个奇怪的行为吗?或者也许我在做错事?
<!DOCTYPE HTML PUBLIC - // W3C // DTD HTML 4.0 Transitional // EN>
< html>
< head>
< script type =text / javascript>
函数redrawThings(){
//从容器中删除所有子项
var cont = document.getElementById(container);
while(cont.childNodes.length> = 1){
cont.removeChild(cont.firstChild);
}
//向容器添加1000个新孩子
for(var i = 0; i <1000; i ++){
var newDiv = document。的createElement( 'DIV');
newDiv.innerHTML =Preved medved+ i;
cont.appendChild(newDiv);
}
}
< / script>
< style type =text / css>
#container {
border:1px solid blue;
}
< / style>
< / head>
< body onload ='setInterval(redrawThings(),200);'>
< div id =container> < / DIV>
< / body>
< / html>
我无法在FF 3.6.8 / Linux,但是对于一个定时器来说,200毫秒是相当小的,那么很多DOM重新渲染。我在机器上注意到的是,除了运行此脚本之外,除了运行此脚本之外,还要执行JavaScript密集型操作,例如在此答案框中输入内存使用情况,但是当我停止输入时,会再次释放(在我的情况下,占用大约16%的内存
我猜,在你的情况下,浏览器的垃圾回收器没有足够的空闲时间才能从内存中实际删除这些节点。
I'm trying to display dynamically changeable data manipulating with DOM elements (adding/removing them). I found out a very strange behavior of almost all browsers: after I removed a DOM element and then add a new one the browser is not freeing the memory taken by the removed DOM item. See the code below to understand what I mean. After we run this page it'll eat step-by-step up to 150 MB of memory. Can anyone explain me this strange behavior? Or maybe I'm doing something wrong?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<script type="text/javascript">
function redrawThings() {
// Removing all the children from the container
var cont = document.getElementById("container");
while ( cont.childNodes.length >= 1 ) {
cont.removeChild(cont.firstChild);
}
// adding 1000 new children to the container
for (var i = 0; i < 1000; i++) {
var newDiv = document.createElement('div');
newDiv.innerHTML = "Preved medved " + i;
cont.appendChild(newDiv);
}
}
</script>
<style type="text/css">
#container {
border: 1px solid blue;
}
</style>
</head>
<body onload='setInterval("redrawThings()", 200);'>
<div id="container"> </div>
</body>
</html>
I can't reproduce this on FF 3.6.8/Linux, but 200 ms for a timer is rather small with that much of DOM re-rendering. What I notice on my machine is that when doing JavaScript-intensive things besides running this script, like typing in this answer box, memory usage increases, but is released again when I stop typing (in my case, to something around 16% of memory usage).
I guess that in your case the browser's garbage collector just doesn't have enough ‘free time’ to actually remove those nodes from memory.
这篇关于循环添加/删除DOM节点会导致JavaScript中的内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!