Mike Flynn
Mike Flynn

Reputation: 24315

Javascript performance and comparing objects vs properties of the object

In javascript is it faster to compare via a property or the entire object that has tons of properties? Below is what I currently have but my object has a ton of properties, and the objects list is quite large. Is it better to create a list from a single property off say id and compare the id of the object? objectids.indexOf(object1.id). Would I see a performance increase?

Comparing Against The Object

objects.indexOf(object1);

function Object() {
  this.id = 1;
  this.name = "test";
}

Upvotes: 1

Views: 618

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138247

Note that both versions aren't equivalent:

  ({ id: 1}) === ({ id: 1 }) // false      
  ({ id: 1}).id === ({ id: 1 }).id // true

If both cases work the same indexOf has to traverse half the array on average to get the index, it doesn't really matter if that array is an array of ids or objects. To get O(1) lookup time use a Set instead.

Upvotes: 1

Related Questions