Array vs. Object efficiency in JavaScript
With ES6 the most performant way would be to use a Map.
var myMap = new Map();
myMap.set(1, 'myVal');
myMap.set(2, { catName: 'Meow', age: 3 });
myMap.get(1);
myMap.get(2);
You can use ES6 features today using a shim (https://github.com/es-shims/es6-shim).
Performance will vary depending on the browser and scenario. But here is one example where Map
is most performant: https://jsperf.com/es6-map-vs-object-properties/2
REFERENCE https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map
It's not really a performance question at all, since arrays and objects work very differently (or are supposed to, at least). Arrays have a continuous index 0..n
, while objects map arbitrary keys to arbitrary values. If you want to supply specific keys, the only choice is an object. If you don't care about the keys, an array it is.
If you try to set arbitrary (numeric) keys on an array, you really have a performance loss, since behaviourally the array will fill in all indexes in-between:
> foo = [];
[]
> foo[100] = 'a';
"a"
> foo
[undefined, undefined, undefined, ..., "a"]
(Note that the array does not actually contain 99 undefined
values, but it will behave this way since you're [supposed to be] iterating the array at some point.)
The literals for both options should make it very clear how they can be used:
var arr = ['foo', 'bar', 'baz']; // no keys, not even the option for it
var obj = { foo : 'bar', baz : 42 }; // associative by its very nature
The short version: Arrays are mostly faster than objects. But there is no 100% correct solution.
Update 2017 - Test and Results
var a1 = [{id: 29938, name: 'name1'}, {id: 32994, name: 'name1'}];
var a2 = [];
a2[29938] = {id: 29938, name: 'name1'};
a2[32994] = {id: 32994, name: 'name1'};
var o = {};
o['29938'] = {id: 29938, name: 'name1'};
o['32994'] = {id: 32994, name: 'name1'};
for (var f = 0; f < 2000; f++) {
var newNo = Math.floor(Math.random()*60000+10000);
if (!o[newNo.toString()]) o[newNo.toString()] = {id: newNo, name: 'test'};
if (!a2[newNo]) a2[newNo] = {id: newNo, name: 'test' };
a1.push({id: newNo, name: 'test'});
}
Original Post - Explanation
There are some misconceptions in your question.
There are no associative arrays in Javascript. Only Arrays and Objects.
These are arrays:
var a1 = [1, 2, 3];
var a2 = ["a", "b", "c"];
var a3 = [];
a3[0] = "a";
a3[1] = "b";
a3[2] = "c";
This is an array, too:
var a3 = [];
a3[29938] = "a";
a3[32994] = "b";
It's basically an array with holes in it, because every array does have continous indexing. It's slower than arrays without holes. But iterating manually through the array is even slower (mostly).
This is an object:
var a3 = {};
a3[29938] = "a";
a3[32994] = "b";
Here is a performance test of three possibilities:
Lookup Array vs Holey Array vs Object Performance Test
An excellent read about these topics at Smashing Magazine: Writing fast memory efficient JavaScript