我需要删除 dom 片段还是垃圾收集器会删除它们?
这可能是一个有点愚蠢的问题。我假设垃圾收集器在函数结束执行后处理任何悬空变量,但我想知道这是否也适用于 DOM 片段。
如果我创建一个 DOM 片段或任何未附加的节点,垃圾收集器会在函数完成执行后删除它吗?
//would this create a memory leak?
setInterval(function exampleScope() {
var unusedDiv = document.createElement('div');
}, 10);
我知道这个例子没有用,但它是我担心的模式的最简单形式。我只是想知道我正在做正确的事。我一直在努力构建一个非常高性能的 JavaScript 游戏引擎,Red Locomotive。我不想添加任何内存泄漏。
This maybe a bit of a silly question. I'm assuming that the garbage collector disposes of any dangling variables after a function ends execution, but I was wondering if this also applies to DOM fragments.
If I create a DOM fragment or any unattached node for that matter, will the garbage collector delete it after the function has finished execution?
//would this create a memory leak?
setInterval(function exampleScope() {
var unusedDiv = document.createElement('div');
}, 10);
I know this example is useless but its the simplest form of the pattern I'm worried about. I just want to know I'm doing the right thing. I've been hard at work building a very high performance JavaScript game engine, Red Locomotive. I don't want to add any memory leaks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
事件处理程序中的 DOM 元素存在 IE 7 内存泄漏: jQuery 泄漏已解决,但为什么呢?
使用其他浏览器应该没问题。请参阅释放 Javascript 中未附加 DOM 节点使用的内存。
如果您非常担心内存泄漏并关心技术文盲的 IE 用户,您应该阅读以下内容: 了解和解决 Internet Explorer 泄漏模式
There is an IE 7 memory leak with DOM elements in event handlers: jQuery leaks solved, but why?
With other browser you should be fine. See Freeing memory used by unattached DOM nodes in Javascript.
If you worry much about memory leaks and care for your tech illiterate IE users, you should read this: Understanding and Solving Internet Explorer Leak Patterns
好吧,这不是 100% 的结论,但我做了一个快速的 JSFiddle 来对此进行实验。这是一个紧密循环,运行您的代码超过 100000000 次。使用 Chrome 任务管理器时,内存使用量从 47.9MB 跃升至 130MB,并保持相当稳定,直到完成后下降至 60MB 左右。
http://jsfiddle.net/u7yPM/
这表明 DOM 节点肯定正在被垃圾收集,否则在整个测试运行过程中,内存使用量将持续增加。
编辑:我在 Chrome 14 上运行了这个。
Well, it's not 100% conclusive but I made a quick JSFiddle to experiment with this. This is a tight loop that runs your code above 100000000 times. Using the Chrome Task Manager memory usage jumped from 47.9MB to 130MB and stayed fairly constant until completed, where it dropped down to 60MB ish.
http://jsfiddle.net/u7yPM/
This suggests that the DOM nodes are definitely being garbage collected, else the memory usage would continue increasing for the whole run of the test.
EDIT: I ran this on Chrome 14.