Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the fourth nested value way slower to access than the fifth? [closed]

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.

enter image description here

Any ideas why this would be happening?

like image 346
stinkycheeseman Avatar asked Dec 01 '25 12:12

stinkycheeseman


2 Answers

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.

like image 162
Claudiu Avatar answered Dec 04 '25 05:12

Claudiu


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.

like image 36
Ted Hopp Avatar answered Dec 04 '25 06:12

Ted Hopp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!