6

请考虑以下javascript。我原以为循环中的分配将允许垃圾收集来防止堆溢出。它在 Firefox 中这样做是正确的,但是在 Chrome(在 OSX 上测试)中,该片段在多次迭代后会导致打开的选项卡崩溃。

    for (var i = 0; i < 1024; ++i) {
            // Allocate a 16mb buffer
            var buffer = new Float32Array(1024*1024*4);

            // Try to explicitly mark it for free by either
            delete buffer;
            // or
            buffer = null;

            console.log(i);
    }

这个脚本本身并没有那么有用。但我正在尝试优化我的 Javascript 应用程序,以使其使用更少的内存。因此,我想听听您的意见。这是 Chrome 中的错误吗?您是否知道在代码执行期间显式调用垃圾收集的任何解决方法(在 FF 和 IE 中它们似乎存在)?谢谢!


编辑:Chrome Inspector 上似乎存在一个名为“收集垃圾”的按钮。它是检查器“时间轴”面板下栏上的第 7 个按钮。这不是表示存在从 Javascript 调用 GC 的方法吗?毕竟,Inspector 的一部分不是用 Javascript 编写的吗?

4

2 回答 2

2

这纯粹是推测,但我想知道垃圾收集是否被推迟到运行循环上的当前项目完成执行。

如果是这样,那么如果你把它塑造成这样,也许它会起作用:

var i = 0;
function allocateArray() {
    var buffer = new Float32Array(1024*1024*4);
    if (++i < 1024) {
        setTimeout(allocateArray, 0); // Post the next call to the run loop
    }
}
allocateArray();
于 2012-09-07T12:59:06.910 回答
0

As far as i know, calling GC doesn't work. You can explicitely call it e.g. in Chrome, but you need to have some debug option enabled, so that's not an option for the finished program.

Here's a Chromium bug about typed arrays not being garbage collected correctly. https://code.google.com/p/chromium/issues/detail?id=232415

I personally have a program right now, where typed arrays are causing huge performance loss in Chrome and minor performance loss in other browsers.

I guess creating new typed arrays frequently should be avoided.(at the current time)

If someone knows more than me on this topic, i would really appreciate it.

于 2014-06-10T10:02:21.217 回答