Reputation: 55
I have an array of JavaScript objects
var arrayObjs = [
{ id:abc123, radius:5.0},
{ id:def235, radius:2.5},...]
I have been using a for loop to find a particular object with id = def235, would it be more efficient to use an object like
var objectObjs = {
{ abc123:{ id:abc123, radius:5.0}},
{ def235:{ id:def235, radius:2.5}},...}
Upvotes: 0
Views: 1905
Reputation: 7498
Just for fun, I tried it: https://jsperf.com/accessor-test-loop-vs-object
Of course, as T.J. described - access by an object property is much faster. Interestingly, on Chrome
the difference is much greater than on Firefox
as I just tried out. Try to run the test of Chrome and Firefox or Edge.
var arrayObjs = [
{ id:'abc123', radius:5.0},
{ id:'def235', radius:2.5}
];
for (var i = 0; i < arrayObjs.length; i++) {
if (arrayObjs[i].id == 'def235') {
// found it
break;
}
}
..VS..
var objectObjs = {
abc123:{ id: 'abc123', radius: 5.0},
def235:{ id: 'def235', radius: 2.5}
}
var found = !!objectObjs.def235;
if (found) {
// ..
}
Upvotes: 0
Reputation: 1074505
would it be more efficient to use an object like
If you're looking up by id
, yes, almost certainly, but your example has an extra layer of {}
you'll want to remove:
var objectObjs = {
abc123:{ id:abc123, radius:5.0},
def235:{ id:def235, radius:2.5},
//...
};
JavaScript objects are highly-optimized for property retrieval by name.
Another option is to use a Map
, which is also optimized for retrieval by key.
If you use an object, probably best to create it via Object.create(null)
so it doesn't inherit Object.prototype
properties. You probably aren't going to look up id
s like toString
or valueOf
, but still... :-) So perhaps:
var objectObjs = Object.assign(Object.create(null), {
abc123:{ id:abc123, radius:5.0},
def235:{ id:def235, radius:2.5},
//...
});
It's also trivial to create that object from your array, to avoid typing the id
s twice and the opportunity for error that introduces:
var arrayObjs = [
{ id:abc123, radius:5.0},
{ id:def235, radius:2.5},/*...*/];
var objectObjs = Object.create(null);
arrayObjs.forEach(entry => { objectObjs[entry.id] = entry; });
Upvotes: 1