loretoparisi loretoparisi - 1 year ago 124
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:

, key:"bla"
, key2:"blabla"

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

objectsList.push( myObj )

having those alternative guards:

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


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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download