Reputation: 10798
I have these two data structures that I continually find myself choosing between when pulling data from a database:
{
"1": {"location": "seattle", "color": "red"},
"2": {"location": "irvine", "color": "blue"},
"3": {"location": "san diego", "color": "green"}
}
{
"listings":[
{"id": "1", "location": "seattle", "color": "red"},
{"id": "2", "location": "irvine", "color": "blue"},
{"id": "3", "location": "san diego", "color": "green"}
]
}
Each seems to have pros and cons...
The object structure is great for quickly accessing a value given an id by saying obj['3'].color
the problem is when listing all objects you have to loop with a for(key in obj)
loop which seems to be very slow.
The array structure loops much faster using for(var i=0; i<array.length; i++)
but accessing a value given an id is not easy out of the box. You have to make a function that loops through the entire array checking the id against a supplied parameter.
Here's a jsperf of the two solutions.
Which do you think is better and why?
Upvotes: 3
Views: 1274
Reputation: 1074495
As always, the answer is: It depends. Will you mostly access the objects randomly by their id
? Then use the object. Will you mostly loop through them in order? Then use an array.
Of course, you can do both, by returning an array and then creating an index on it by id
value. E.g.,
var arr = /*...wherever you get your second example, the array...*/;
var index, len, entry;
arr.index = {};
for (index = 0, len = arr.length; index < len; ++index) {
entry = arr[index];
arr.index[entry.id] = entry;
}
(I have a function that does this because I find it a useful technique periodically.)
Now you can loop through them with a loop, or randomly access them via arr.index["some_id"]
. Note that you have to be careful when modifying it (e.g., ensure you do deletions and additions in both places).
Note that there I've used a property on the actual array, called index
(the name can be whatever you like; I frequently use index
or byId
or similar). Some people don't like to use non-index properties on arrays; I have no problem with it, since arrays are really just objects anyway. But you don't have to, you can keep track of the index in its own variable as a peer of arr
.
Also note that while there may be an absolute difference in the speed of iteration using for..in
on the object vs. for
on the array, the odds of there being any real-world impact on that speed of iteration is very low.
Upvotes: 1