Stack Overflow Asked by Ron BELLAICHE on December 31, 2020
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?
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})
Or:
{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
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP