Skip to content Skip to sidebar Skip to footer

Memory Overhead Of Empty Array Vs Undefined Var?

var Arr1; var Arr2 = []; (Assume Arr1 starts as an undefined var and it becomes an array later as needed.) Would a billion of Arr1 have the same memory footprint as a billion of A

Solution 1:

TL;DR: about 90 bytes.


I took some measurements in Firefox and Chrome (both on Windows, 64-bit). Firefox’s are much more precise thanks to about:memory, but the impression you get in Chrome is also clear. (I took several measurements after loading the page and waiting for it to settle, then took the best of them.)

My test document contained a doctype and one script block only.

  • Baseline (no arrays):

    var x = [];
    for (var i = 0; i < 0; i++) {
        x.push([]);
    }
    

    Firefox: js-realm memory usage is 0.60 MB.

    Chrome: memory footprint for the tab is 20,880K.

  • A million undefineds or nulls: (memory footprints were the same)

    var x = [];
    for (var i = 0; i < 1000000; i++) {
        x.push(undefined);  // or x.push(null)
    }
    

    Firefox: js-realm memory usage is 8.1 MB, of which class(Array)/objects is 8.00MB, all malloc-heap. (That suggests that it allocated one word for each of the million indexes in the containing array.)

    Chrome: memory footprint for the tab is 31,020K. (Sounds like about 10 bytes per undefined.)

  • A million arrays:

    var x = [];
    for (var i = 0; i < 1000000; i++) {
        x.push([]);
    }
    

    Firefox: js-realm memory usage is 99.65 MB, of which class(Array)/objects is 99.55 MB, of which 91.55 MB is gc-heap and 8.00 MB is malloc-heap. Sounds like about 96 bytes (12 words) per empty array.

    Chrome: memory footprint for the tab is 116,164K. Roughly the same overhead as Firefox.

So there you are: it looks like you get roughly 90 bytes of overhead per [], compared with using undefined or null.

Solution 2:

var Arr1 creates a memory footprint that holds a reference to nothing. So, yes, there is a cost to this, but it is minimal.

But, var Arr2 = [] creates a memory address that is holding a reference to a new Array object, so there is more of a footprint there. Even though the array is empty, it is a unique instance of an Array object, which, itself uses the single Array.prototype to inherit from. It's the population of the Array that will really take up memory, since even a billion empty arrays don't have to store anything that is not already being stored by Array.prototype. Even with a billion empty arrays, they all inherit from just one Array.prototype object and that is where the native API for arrays is stored.

Post a Comment for "Memory Overhead Of Empty Array Vs Undefined Var?"