Which takes less memory: a Javascript array or Javascript object?

If I have a Javascript list which will have only numeric keys, which takes less memory?

var array = [];
array[0] = 'hello';
array[5] = 'world';
array[50] = 'foobar';

var obj = {};
obj[0] = 'hello';
obj[5] = 'world';
obj[50] = 'foobar';

I don't know a ton about Javascript engine internals, so...

The reason I ask is because that array, when converted to a string, will have a bunch of undefined's in the middle of it. Are those actually stored in some fashion, or is that just put in at string conversion?



An array is basically an ordered set of values associated with a single variable name.

In your example I think you try to do an associative array, and you should use object, Array is not meant to be used for key/value pairs.

Also the array length is indirecly increased when you assign a value to an index with higher length of the current array length:

var array = new Array();
array[99] = "Test";
// array.length is now 100

Check this detailed article on the subject.


JavaScript doesn't implement arrays like other languages so you don't get any performance enhancements inherent of a normal array (memory-wise); in JavaScript an array is very similar to an object; actually, it is essentially an object just with a few extra methods and capabilities (such as a length that updates itself). I'd say neither is quicker.


Probably the Javascript array because you can 'only' use numeric key values, where as the object literals provide a space for key values, and even if you use numerical key values, they are probably handled differently than the numerical key values for arrays.

Most likely the reason arrays can't have text-based key values are because they are treated differently than object literals. I'm guessing that because they are probably treated differently, the processing for the array probably is more optimized for numeric key values, were as a object literal is optimized to use strings or numbers as their keys.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.