开发者

Does this code have a memory leak? If so, how do i remove it?

I am given with a project that my seniors worked on, this project is developed keeping in mind that the whole page should never be reloaded. So obviously everything went into ajax. And it has 100's of lines that go something like this.

 function iCreateProblems()
    {
        //some rubbish
        document.getElementById('some_rubbish').innerHTML=obj1.re开发者_开发问答sponseText;
    }

and a typical response text is "<div onClick="handleMe()">some thing stupid</div>"; There are three main div's on the page and everything is repeatedly loaded and reloaded into these div's. Now as far as i understand, this will clearly give away to memory leak, right? So how do i fix this? There are about 8000 lines of code that go in this manner. Is there a way i can fix the memory leak? There are hundreds of handlers that are assigned like this. What do i do now?


No, it shouldn't. You do not handle memory directly in js; garbage collectors remove everthing unneeded and you don't need to explicitly delete on divs' contents if you overwrite the content.


Without seeing the rest of the code there's no way to tell. Despite what people are saying here, it's very easy to create a memory leak in JS and not notice it. The way JS garbage collectors usually work is by marking variables that are "reachable". Variables become considered "unreachable" when their "mark" is taken off and not reapplied, (which is to say, they're completely unreachable by any of the programmer's functions or scopes). After the mark is removed, they're eventually cleaned up by the garbage collector.

One contrived example of a memory leak would be:

(function() {
  var xhr = $.get('http://google.com/');
  $('a').click(function() {
    console.log('hello');
  });
})();

As long as that element exists on the page, with that event listener bound to it, the variable xhr will never be cleaned up by the garbage collector. Even though xhr is never used anywhere in your code, the garbage collector will refuse to clean it up because it is still "reachable" by your event listener.

edit: I should also mention, there is also the possibility of a memory leak occurring from bugs in a poorly written JS engine. (See also: Internet Explorer). Most DOM libraries account for this and make sure to avoid these problems, but it can still happen. For these memory leaks you need to find a workaround for that particular engine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜