Memory leaks and closures in JavaScript - when and why?

前端 未结 3 360
感情败类
感情败类 2020-12-12 10:35

You quite often read on the web that using closures is a massive source of memory leaks in JavaScript. Most of the times these articles refer to mixing script code and DOM e

3条回答
  •  醉梦人生
    2020-12-12 11:39

    I have to disagree with closures being a cause of memory leaks. This maybe true for older versions of IE because of its shoddy garbage collection. Please read this article from Douglas Crockford, which clearly states what a memory leak is.

    The memory that is not reclaimed is said to have leaked.

    Leaks are not the problem, efficient garbage collection is. Leaks can happen in both browser and server JavaScript applications alike. Take V8 as an example. In the browser, garbage collection happens on a tab when you switch to different window/tab. The leak is plugged when idle. Tabs can be idle.

    On the server things are not so easy. Leaks can happen, but GC is not as cost-effective. Servers cannot afford to GC frequently or its performance will be affected. When a node process reaches a certain memory usage, it kicks in the GC. Leaks will then be removed periodically. But leaks still can happen at a faster rate, causing programs to crash.

提交回复
热议问题