In a JavaScript app, suppose I have a nested object like this:
var myObject = {
someProp: {
someOtherProp: {
anotherOne: {
yetAnother: {
myValue: "hello!"
}
}
}
}
}
In another part of the code, I'm calling myValue
multiple times (I just call it three times in this example but imagine there's a lot more):
someFunc() {
doSomething(myObject.someProp.someOtherProp.anotherOne.yetAnother.myValue)
doSomethingElse({
arg1: "something",
arg2: myObject.someProp.someOtherProp.anotherOne.yetAnother.myValue
})
if (myObject.someProp.someOtherProp.anotherOne.yetAnother.myValue == "hola") {
doStuff()
}
}
Apart from the obvious readability and maintainability gains, is it actually faster to do it like this:
someFunc() {
let val = myObject.someProp.someOtherProp.anotherOne.yetAnother.myValue
doSomething(val)
doSomethingElse({
arg1: "something",
arg2: val
})
if (val == "hola") {
doStuff()
}
}
Or is it pretty much the same, behind the scenes?
In other words, does the interpreter have to walk the whole myObject
tree and search for each nested property each time, in case 1, or does it somehow cache the value, or is there another mechanism that makes it as fast as case 2?
Context: any modern browser (Chrome, Safari, Firefox, Edge).