对哦,那style="border:1px solid #FF0000"这些没有用指针的,应该不会有内存泄漏吧。也就是说如果 var div1 = document.createElement("DIV"); var div2 = document.createElement("DIV"); div1.appendChild(div2); document.body.appendChild(div1); 这样的话,无论怎么的插入顺序也不会有内存泄漏吧。
我觉得可能CPU的时间用在初始化函数上了,如果换成下面这样就会比原来的时间快一些。使用下面的方法CPU100%应该已经不是函数的问题了,因为可以看到使用style="border:1px solid #FF0000"这个时候也是需要一定的时间,因为生成的量比较大。虽然使用下面的方法会快,但是foo函数如果不定义会出错,也就是说foo函数在下面的例子中是已经初始化了的,所以后面执行会变快 <div id="hostElement"> </div> <script language=javascript> function foo() { } function LeakMemory() { var hostElement = document.getElementById("hostElement"); // Do it a lot, look at Task Manager for memory response for(i = 0; i < 5000; i++) { var parentDiv =document.createElement("<div>"); //document.createElement("<div onclick='foo()'>");
parentDiv.onclick=foo; var childDiv =document.createElement("<div>"); //document.createElement("<div onclick='foo()'>");
childDiv.onclick=foo; // This will leak a temporary object parentDiv.appendChild(childDiv); hostElement.appendChild(parentDiv); hostElement.removeChild(parentDiv); parentDiv.removeChild(childDiv); parentDiv = null; childDiv = null; } hostElement = null; alert("done") } LeakMemory(); </script>
var div1 = document.createElement("DIV");
var div2 = document.createElement("DIV");
div1.appendChild(div2);
document.body.appendChild(div1);
这样的话,无论怎么的插入顺序也不会有内存泄漏吧。
<div id="hostElement">
</div>
<script language=javascript>
function foo()
{
}
function LeakMemory()
{
var hostElement = document.getElementById("hostElement"); // Do it a lot, look at Task Manager for memory response for(i = 0; i < 5000; i++)
{
var parentDiv =document.createElement("<div>");
//document.createElement("<div onclick='foo()'>");
parentDiv.onclick=foo;
var childDiv =document.createElement("<div>");
//document.createElement("<div onclick='foo()'>");
childDiv.onclick=foo; // This will leak a temporary object
parentDiv.appendChild(childDiv);
hostElement.appendChild(parentDiv);
hostElement.removeChild(parentDiv);
parentDiv.removeChild(childDiv);
parentDiv = null;
childDiv = null;
}
hostElement = null;
alert("done")
}
LeakMemory();
</script>
parentDiv.appendChild(childDiv);
hostElement.appendChild(parentDiv);
hostElement.removeChild(parentDiv);
parentDiv.removeChild(childDiv);这几句注释掉才恐怖呢。离开页面内存都不能释放。连刷几次就占光你内存了。