I have a question about how object key-value work when we get value by key? Does it need to lookup where the key first and return the corresponding value?
For example: If we have object like
var obj = { keyX: valueX, keyY: valueY, keyZ: valueZ }
Then we retrieve the value obj.keyY, so does it lookup one by one on those object keys to find for keyY? So for large object (e.g object with 1 million keys), is it slow when we get value by key?
I appreciate any helps. Thank you.
Then we retrieve the value obj.keyY, so does it lookup one by one on those object keys to find for keyY?
It's up to the implementation, but even in old JavaScript engines, the answer is no, it's much, much more efficient than that. Object property access is a hugely common operation, so JavaScript engines aggressively optimize it, and are quite sophisticated at doing so.
In modern JavaScript engines objects are often optimized to just-in-time generated class machine code, so property lookup is blindingly fast. If they aren't optimized for some reason (perhaps only used infrequently), typically a structure like a hash table is used, so lookup remains much better than linear access (looking at each property).
Objects with large numbers of properties, or properties that vary over time, may not be as well optimized as objects with more reasonable numbers of properties. But they'll at least be optimized (in anything vaguely modern) to a hash table level of access time. (FWIW: For objects that have varying properties over time, you may be better off with a Map
in the first place.)
Although interesting academically, don't worry about this in terms of writing your code until/unless you run into a performance problem that you trace to slow property access. (Which I literally never have in ~20 years of JavaScript coding. :-) )
Little benchmark:
//setup..
for(var obj = {}, i =0; i<1000000; obj['key'+i] = i++);
var a;
//find 1
console.time(1);
a = obj.key1;
console.timeEnd(1);
//find last
console.time(2);
a = obj.key999999;
console.timeEnd(2);
As you see, it is not lookup one by one
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With