TE
科技回声
首页24小时热榜最新最佳问答展示工作
GitHubTwitter
首页

科技回声

基于 Next.js 构建的科技新闻平台,提供全球科技新闻和讨论内容。

GitHubTwitter

首页

首页最新最佳问答展示工作

资源链接

HackerNews API原版 HackerNewsNext.js

© 2025 科技回声. 版权所有。

How JavaScript closures are garbage collected

91 点作者 rohshall超过 11 年前

5 条评论

pfraze超过 11 年前
I&#x27;m fairly sure the issue being illustrated here is due to an optimization in how closure scopes are created, which I don&#x27;t think any of the answers mention (yet). Can&#x27;t remember where I saw this, but there&#x27;s a blog-post somewhere in the wild that explains. Slap me if I&#x27;m wrong.<p><pre><code> &#x2F;&#x2F; scope 1 var someClass = function() {}; function f() { &#x2F;&#x2F; scope 1, 2 var some = new someClass(); function unreachable() { some; &#x2F;* scope 1, 2, 3 *&#x2F; } return function() { &#x2F;* scope 1, 2, 4 *&#x2F; }; } window.f_ = f(); </code></pre> Basically, any closures created within scope 2 will share the same parent scope in its scope chain rather than each closure having its own parent. That means any variable in scope 2 that&#x27;s captured by a child closure (3 or 4) will be included in the other child scopes.<p>In this case, `some` is captured in `unreachable()`, thus it&#x27;s going to be included in the returned function as well. The returned function is then retained with `window.f_`, and that&#x27;s the leak.<p>EDIT: for clarity. EDIT2: not the original article I read, but this does cover it: <a href="http://www.meteor.com/blog/2013/08/13/an-interesting-kind-of-javascript-memory-leak" rel="nofollow">http:&#x2F;&#x2F;www.meteor.com&#x2F;blog&#x2F;2013&#x2F;08&#x2F;13&#x2F;an-interesting-kind-of...</a>
评论 #6724283 未加载
评论 #6723529 未加载
评论 #6724094 未加载
评论 #6723002 未加载
i_s超过 11 年前
The author wrote a really short code snippet that demonstrates the problem:<p><pre><code> function f() { var some = []; while(some.length &lt; 1e6) { some.push(some.length); } function g() { some; } &#x2F;&#x2F;removing this fixes a massive memory leak return function() {}; &#x2F;&#x2F;or removing this } </code></pre> If you keep a reference to the results of calling this function, it will keep a reference to the &quot;some&quot; variable, even though it is not needed.<p>He created a page that demonstrates the problem here:<p><a href="https://s3.amazonaws.com/chromebugs/memory.html" rel="nofollow">https:&#x2F;&#x2F;s3.amazonaws.com&#x2F;chromebugs&#x2F;memory.html</a>
评论 #6724542 未加载
paulddraper超过 11 年前
Unfortunately, this behavior is common across all major browsers. There is a Chromium bug for it (<a href="http://crbug.com/315190" rel="nofollow">http:&#x2F;&#x2F;crbug.com&#x2F;315190</a>), but no responses as of yet.
评论 #6724520 未加载
martin-adams超过 11 年前
Maybe it&#x27;s being kept in case the returned function executes an eval statement which needs the closure ;)
talles超过 11 年前
Ah gc... always behaving as something alive<p>good question by the way