Is it more effective to utilize an object like this?
If you're searching by id
, then yes, it is likely more efficient. However, in your example, there is an extra layer of {}
that should be removed:
var objectObjs = {
abc123:{ id:abc123, radius:5.0},
def235:{ id:def235, radius:2.5},
//...
};
JavaScript objects are optimized for property retrieval by name.
Another option is to use a Map
, which is also designed for efficient retrieval by key.
If you decide to use an object, it's best to create it using Object.create(null)
to prevent inheriting Object.prototype
properties. Although you may not look up id
s like toString
or valueOf
, it's still a good practice:
var objectObjs = Object.assign(Object.create(null), {
abc123:{ id:abc123, radius:5.0},
def235:{ id:def235, radius:2.5},
//...
});
You can easily create this object from your array to avoid duplicating the id
s and the potential for mistakes:
var arrayObjs = [
{ id:abc123, radius:5.0},
{ id:def235, radius:2.5},/*...*/];
var objectObjs = Object.create(null);
arrayObjs.forEach(entry => { objectObjs[entry.id] = entry; });