I have a model with possibly thousands of objects. I was wondering what would be the most efficient way of storing them and retrieving a single object once I have it's id. The id's are long numbers.
So these are the 2 options I was thinking about. in option one it's a simple array with an incrementing index. in option 2 it's an associative array and maybe an object, if it makes a difference. My question is which one is more efficient, when I mostly need to retrieve a single object, but also sometimes loop through them and sort.
Option one with non associative array:
var a = [{id: 29938, name: 'name1'},
{id: 32994, name: 'name1'}];
function getObject(id) {
for (var i=0; i < a.length; i++) {
if (a[i].id == id)
return a[i];
}
}
Option two with associative array:
var a = []; // maybe {} makes a difference?
a[29938] = {id: 29938, name: 'name1'};
a[32994] = {id: 32994, name: 'name1'};
function getObject(id) {
return a[id];
}
Update:
OK, I get that using an array in the second option is out of the question. So the declaration line the second option should really be: var a = {};
and the only question is: what is performing better in retrieving an object with a given id: an array or an object where the id is the key.
and also, will the answer change if i will have to sort the list many times?
The short version: Arrays are mostly faster than objects. But there is no 100% correct solution.
Update 2017 - Test and Results
Original Post - Explanation
There are some misconceptions in your question.
There are no associative arrays in Javascript. Only Arrays and Objects.
These are arrays:
This is an array, too:
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:
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
I tried to take this to the next dimension, literally.
Given a 2 dimensional array, in which the x and y axes are always the same length, is it faster to:
a) look up the cell by creating a two dimensional array and looking up the first index, followed by the second index, i.e:
or
b) create an object with a string representation of the x and y coordinates, and then do a single lookup on that obj, i.e:
Result:
Turns out that it's much faster to do two numeric index lookups on the arrays, than one property lookup on the object.
Results here:
http://jsperf.com/arr-vs-obj-lookup-2