Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does null occupy memory in javascript?

I've got the following situation:

var large = [a,b,c,d,e,f,g,h,i];
var small = [a2, b2, c2, null, null, null, null, null, null, i2];

where every element of both arrays is an object.

The small array contains information related to the the larger one, but not every element of large requires an associated element in small and so I set it to null. However, I do still need to keep the indices the same so I can do things like large[16].id + ': ' + small[16].description. Does the fact that I've got an array that's mostly null in value result in increased memory usage?

My question is whether or not I'd be better off doing something like small = [a2,b2,c2,i2], and setting indices in properties like a2.index = 0; b2.index = 1 and so on.

I've also come across a suggestion to use undefined instead and someone even mentioned implementing linked lists. I don't think I need to implement a linked list since I'm not adding or removing elements very often.

like image 532
Radu Avatar asked Sep 07 '25 15:09

Radu


1 Answers

Arrays are actually Objects with special treatment of properties with names that are array indexes.

By assigning 'null', you bring each property into existence, which will use a non-zero amount of memory and as mentioned already slow down lookups.

You can elide the non-existent members instead, which will result in a sparse array:

var small = [a2, b2, c2,,,,,,, i2];
// small == [a2, b2, c2,undefined,undefined,undefined,undefined,undefined,undefined, i2]

Edit Note that undefined does take space if you explicitly assign it to an array element (or any variable). To reclaim memory in this case, you will need to explicitly delete the element. The initialization style shown in my code sample never assigns anything to the elided elements, so they do not exist at all. This can be confirmed by checking for those elements' existence as properties of the array object:

// continued from above
small.hasOwnProperty('3'); // returns false

small[3] = undefined;
small.hasOwnProperty('3'); // now returns true because the property exists

delete small[3];
small.hasOwnProperty('3'); // returns false again

alert(small.length); // alerts '10', showing that the array itself is still intact.
like image 68
codelahoma Avatar answered Sep 10 '25 07:09

codelahoma