Memory leak in javascript when using new Image()

后端 未结 1 382
醉梦人生
醉梦人生 2021-01-07 02:51

I seem to have a memory leak, caused by using the \'new Image()\' in a javascript script. If I watch the used physical memory in the windows resource monitor, i get the expe

相关标签:
1条回答
  • 2021-01-07 02:57

    First off, there is no browser that I know of that leaks when you go to another page just because you have images stored in a JS array.

    There are some older browsers that leak if you have circular references between DOM <==> JS where some javascript refers to a DOM element and a custom attribute on the DOM element refers back to the same javacript object, but that does not appear to be what you have here.

    So ... I'd be surprised if what you're seeing is actually a leak in going from one page to the next. If you're convinced it is, then create either a plain web page that you can share with us or a jsFiddle that shows the issue and tell us what exact browser you're testing in and exactly how you're measuring the memory usage that determines you have a leak.

    For it to truly be a leak, you have to consistently see memory usage go up and and up and up, every time you go to the page over and over again. Just because total memory usage is a little bit higher the second time you go to the page does not mean you have a leak. The browser has some data structures that grow (to a point) with usage like the memory-based cache, the session browsing history, etc... that are not indicative of leaks.

    Second off, I don't see anything in the data structures you've shown that are illustrative of the kinds of circular references that are known to cause leaks in older browsers.

    Third off, the delete operator is for removing properties from an object. That's all it's for. See these articles: Understanding Delete and MDN Delete for a lot more explanation. So, your cleanup code in the unload handler is not using delete properly. You cannot delete vars or array elements with delete. Though I can't see any reason why this code is necessary, if you were going to have it, it would be like this:

    // allow garbage collection by removing references
    $(window).unload(function() {
        for (var i = 0; i < imgObjs.length; i++) {
            imgObjs[i] = null;
        }
        imgObjs = null;
    }
    
    0 讨论(0)
提交回复
热议问题