I was building a jsperf to illustrate time it took to access nested object members and I found this strange phenomenon. For some reason, the test run drastically slower for the fourth-nested object member than the fifth. I've tried this in Chrome and Firefox and am getting the same results.

Any ideas why this would be happening?
Your object is this, my comment added:
var obj = {
"one": {
"two": {
"three": {
"four": {
"five": {
"value": 0
}
/* MISSING "value": 0 */
},
"value": 0
},
"value": 0
},
"value": 0
},
"value": 0
};
};
The object at the "four" key doesn't have a "value" key, however, so apparently the JavaScript engine(s) have to do extra work to handle that case: miss the key look-up on the object, miss the key look-up on the object's prototype Object, return undefined, and then compute NaN when you add 1 to undefined.
The problem is that obj.one.two.three.four does not have a value attribute. In that one case, JavaScript traverses the prototype chain looking for the missing attribute before finally assigning NaN to sum.
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