网络编程
位置:首页>> 网络编程>> JavaScript>> GC与JS内存泄露(5)

GC与JS内存泄露(5)

作者:alucard 来源:Alibaba.com UED 发布时间:2010-09-25 19:01:00 

标签:内存,js,javascript,IE

三、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这两段函数的唯一区别就在于他们的代码的循序,从代码上看,两段代码的逻辑都没有错。

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com