Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 721
Matchu Avatar asked Aug 07 '09 21:08

Matchu


People also ask

Which is faster array or object in JS?

The short version: Arrays are mostly faster than objects.

How much memory does a JavaScript object use?

JavaScript uses double-precision (64-bit) floating point numbers. 64 bits are 8 bytes, but each number actually takes up an average of 9.7 bytes. Likewise, Chrome shows the size of each individual empty array as 32 bytes and the size of each empty object as 56 bytes.

Why are JavaScript objects better than arrays?

Both objects and arrays are considered “special” in JavaScript. Objects represent a special data type that is mutable and can be used to store a collection of data (rather than just a single value). Arrays are a special type of variable that is also mutable and can also be used to store a list of values.

Should I use object or array?

Think about what your particular data represents: If it's a single entity with named properties, you want an object. If it's a group of entities of the same type/shape, or if order matters, you likely want an array.


1 Answers

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.

like image 95
Christian C. Salvadó Avatar answered Sep 28 '22 02:09

Christian C. Salvadó