tags:

views:

427

answers:

3

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?

A: 

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.

Chacha102
Arrays CAN have "text-based key values" ... Arrays are just objects (in JS at least).
J-P
+4  A: 

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.

CMS
One of those good answers where, rather than asking the stated question (Which is quicker?), skips straight up the chain to the real question (Which should I use?). Thanks!
Matchu
You are welcome Matchu!
CMS
+1  A: 

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.

J-P
That's incorrect -- all JS implementations have "efficient" implementations of arrays, at least they are substantially more efficient than normal objects.They all assume that a compact array is the norm, and a sparse array is uncommon, and for the reason optimise for "normal" array usage.Very simple perf testing would have shown that :D
olliej