-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?

4
  • 1
    Which has better performances and why? Benchmarking would tell for sure. Commented Nov 23, 2016 at 16:31
  • so it's not a good SO question? not sure maybe not, 2 downvotes but don't getting the reason. Commented Nov 23, 2016 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. Commented Nov 23, 2016 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? Commented Nov 23, 2016 at 16:37

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.