三、Cross-Page-Leaks
仍然先看一个例子:
< html > < head > < script language = “ JScript “ > 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 onClick=’foo()’> “ ); var childDiv = document.createElement( “ <div 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 ; } function CleanMemory() { 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 onClick=’foo()’> “ ); var childDiv = document.createElement( “ <div onClick=’foo()’> “ ); // Changing the order is important, this won’t leak hostElement.appendChild(parentDiv); parentDiv.appendChild(childDiv); hostElement.removeChild(parentDiv); parentDiv.removeChild(childDiv); parentDiv = null ; childDiv = null ; } hostElement = null ; } </ script > </ head > < body > < button onclick = “ LeakMemory() “ > Memory Leaking Insert </ button > < button onclick = “ CleanMemory() “ > Clean Insert </ button > < div id = “ hostElement “ ></ div > </ body > </ html >
LeakMemory和CleanMemory这两段函数的唯一区别就在于他们的代码的循序,从代码上看,两段代码的逻辑都没有错。
出处:alibaba.com中国站
责任编辑:bluehearts
上一页 GC与JS内存泄露 [4] 下一页 GC与JS内存泄露 [6]
◎进入论坛网页制作、WEB标准化版块参加讨论,我还想发表评论。
|