Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How object basically work when get value by key

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.

like image 256
Quoc Van Tang Avatar asked Sep 21 '25 00:09

Quoc Van Tang


2 Answers

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. :-) )

like image 198
T.J. Crowder Avatar answered Sep 22 '25 12:09

T.J. Crowder


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

like image 23
Darth Avatar answered Sep 22 '25 12:09

Darth