三、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這兩段函數(shù)的唯一區(qū)別就在于他們的代碼的循序,從代碼上看,兩段代碼的邏輯都沒有錯。
出處:alibaba.com中國站
責(zé)任編輯:bluehearts
上一頁 GC與JS內(nèi)存泄露 [4] 下一頁 GC與JS內(nèi)存泄露 [6]
◎進入論壇網(wǎng)頁制作、WEB標準化版塊參加討論,我還想發(fā)表評論。
|