-2

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?

loretoparisi
  • 15,724
  • 11
  • 102
  • 146
  • 1
    *Which has better performances and why?* Benchmarking would tell for sure. – Frédéric Hamidi Nov 23 '16 at 16:31
  • so it's not a good SO question? not sure maybe not, 2 downvotes but don't getting the reason. – loretoparisi Nov 23 '16 at 16:34
  • I'm afraid it isn't. Performance advice depends on many things and is very hard to get right in the general case. Specifics about your platform can make any attempt at answering correctly moot. That's why I usually suggest benchmarking the code yourself instead of attempting to guess (most probably wrongly) the "best" approach. – Frédéric Hamidi Nov 23 '16 at 16:35
  • Ok this right, but what about JavaScript `Array` and `Object` and `.indexOf` usage / performances? This it is not related to the platform, right? – loretoparisi Nov 23 '16 at 16:37

1 Answers1

1

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.

Community
  • 1
  • 1
Adam Leggett
  • 3,714
  • 30
  • 24
  • Thanks this is the right answer, so this confirms as well that this is a valid SO question or better a duplicate, and I will mark like that. – loretoparisi Nov 23 '16 at 16:42