Javascript garbage collection of typed arrays in C

2019-06-23 22:01发布

问题:

Please consider the following javascript. I would have thought that the allocation in the loop would allow for garbaging collection to kick in preventing to overflow the heap. It rightly does so in Firefox, however in Chrome (tested on OSX) the snippet crashes the open tab after several iterations.

    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);
    }

In itself this script it not all that useful. But I am trying to optimize my Javascript application in order for it to use less memory. Therefore I'd like your opinion. Is this a bug in Chrome? Do you know of any workarounds to explicitly call the garbage collection during code execution (in FF and IE they seem to exist)? Thanks!


Edit: There appears to exist a button on the Chrome Inspector called "Collect Garbage". It is the 7th button on the lower bar on the "Timeline" panel of the Inspector. Doesn't this signify that a way exist to call GC from Javascript? After all, aren't parts of the Inspector written in Javascript?

回答1:

This is pure speculation, but I wonder whether the garbage collection is being postponed until the the current item on the run loop finishes executing.

If so, then perhaps it would work if you shaped it like this:

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();


回答2:

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.