loretoparisi loretoparisi - 10 days ago 6
Javascript Question

JavaScript associative array and Array.indexOf lookup

Supposed to have a 100,000 items or more array of objects, with unique ids like:

myObj={
id:makeUniqueId()
, key:"bla"
, key2:"blabla"
}


and I have to put these object in ad array with unique ids by
myObj.id
, so I would do like

objectsList.push( myObj )


having those alternative guards:

if(typeof( objectsIdMap[ myObj.id ] )=="undefined" ) {
objectsIdMap[ myObj.id ]={};
objectsList.push( myObj );
}


and

if( objectsIdList.indexOf( myObj.id) < 0 ) {
objectsIdList.push( myObj.id );
objectsList.push( myObj );
}


Which has better performances and why? Any productive way to achieve better performances using
Set
or
Map
?

Answer

The replies you got to the effect that the only way to really know is to benchmark it yourself are true. However, this subject has been explored before:

In JS, which is faster: Object's "in" operator or Array's indexof?

The bottom line is that the typeof obj[id] method is usually faster.

Comments