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).
Is it faster to make a dedicated variable instead of calling deeply nested object several times?
javascript;computer science
The optimization you are performing by hand is called common subexpression elimination.  According to this article, Chrome's V8 has performed this operation since at least 2011; Webkit's JIT also does it; SpiderMonkey, the JS engine in Firefox also does it.  I haven't found a good description of the optimization performed by Chakra, Edge's JIT, but the source code is online and the function located here appears to perform the relevant optimization.It therefore seems that there is little point in doing this for optimization purposes (at least for desktop browsers -- note that mobile browsers in many cases do not have JIT compilers, or if they do they are much more basic).  But it's probably worth doing anyway in order to make your code more readable.