1

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";
}
9
  • 1
    How do you plan on comparing the entire object? In any case, comparing a unique identifier would be the way to go. Commented Dec 7, 2018 at 20:32
  • comparing numbers is faster than comparing objects. Commented Dec 7, 2018 at 20:32
  • 4
    indexOf will compare object references, so you'd need to show how you're populating objects to know if it would even work... Commented Dec 7, 2018 at 20:36
  • jsperf.com make tests and find out Commented Dec 7, 2018 at 20:45
  • jsfiddle.net/qx6wgem0/5 - Admittedly this may not be entirely correct, however from running the tests 10000 times on a dataset of 20000 simple objects, it looks like doing an indexOf by object reference is roughly twice as fast as doing an indexOf by ID. Commented Dec 7, 2018 at 21:03

1 Answer 1

1

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.