Object comparison Complexity Javascript

I would like to compare the performances of comparing two objects in JavaScript having a unique id ‘key’ using their key or equality sign i.e: object1 === object2 or object1.key === object2.key.

While both are working I am wondering is it better to compare directly the keys as it will have only two values to compare or is Javascipt comparing each key / value in each value and then the complexity would be O(n) (n being the muber of keys of an object)

Is it comparing addresses or something to make it efficient?

Stack Overflow Asked by Ron BELLAICHE on December 31, 2020

1 Answers

One Answer

Case 1. comparing distinct objects:

While both are working

Well they don't :

{a: 1} == {a: 1} // false

you can't compare two distinct objects by two (or three) equal sign. you have two way:

JSON.stringify({a: 1}) === JSON.stringify({a: 1})


{key: 1, a: 1}.key === {key: 1, a: 1}.key

Which obviously the second one is more efficient.

Case 2. Comparing non-distinct objects like:

var obj1 = {key: 1, a: 1, b: 2}
var obj2 = {key: 2, a: 1, b: 2}
var obj3 = obj1
obj3 === obj1 // true

There is no difference between comparing them directly or comparing them by your keys, both are O(1) since js will compare them by refrence, not by comparing their key-values.

Correct answer by yaya on December 31, 2020

Add your own answers!

Related Questions

Call parent class method (with this context) in child class

2  Asked on December 27, 2021 by rjoxford


Replace .(dot) inside number Java between two elements

2  Asked on December 27, 2021 by alex-danilov


Filtering an array of objects Vue

2  Asked on December 27, 2021 by graham-morby


Is there any good idea to ceil or floor datetime in python3?

2  Asked on December 27, 2021 by asknature


How do I use django’s Q with django taggit?

4  Asked on December 27, 2021 by shino


When to use UserPassesTestMixin vs PermissionRequiredMixin

2  Asked on December 27, 2021 by david-jay-brady


nuxt: pass data from server plugin to client

1  Asked on December 27, 2021


Am I Using JDBC Connection Pooling?

4  Asked on December 27, 2021 by ryandlf


Ask a Question

Get help from others!

© 2022 All rights reserved.