Skip to content Skip to sidebar Skip to footer

Lots Of Null Values In An Array Mean Any Harm?

var arr = []; arr[50] = 'foo'; arr[10000] = 'boo';

Solution 1:

Depends on the implementation. This:

arr=[]
arr[1000]=1
arr[1000000000]=2
arr.sort()

will give [1,2] on Chrome (in no more time then sorting a dense array with two elements), but an allocation size overflow error on Firefox.

Solution 2:

No harm at all. Just make sure you are testing if the value is defined before using it though.

Solution 3:

Consider working with "key/value array" for such thing:

var arr = {};
arr[50] = 'foo';
arr[10000] = 'boo';

Having this you lose the ability to detect the array length (arr.length will be undefined) and you can iterate it using different kind of loop, but if you don't need any of those IMO that's better way.

Solution 4:

No. Most JavaScript implementations will allocate two slots (i.e. the array will allocate the same amount of memory as if it had just two elements with the indexes 0 and 1).

Post a Comment for "Lots Of Null Values In An Array Mean Any Harm?"