JavaScript: is it faster to cache deeply nested variables?
javascript, performance
Solution
As with all performance questions of importance, it is always best to test your specific situation in a tool like jsperf.com so you can measure the exact situation you care about and you should also run the test in multiple browsers to make sure what you're measuring is a general characteristic of the language implementation, not just a peculiarity to one browser.
In answer to your question, it is generally faster to cache a deep object reference if you are going to be accessing it multiple times.
In the specific example, I coded here: http://jsperf.com/cache-deep-reference, the cached reference was more than 2x faster in chrome and more than 4x faster in IE10.
Problem
Let's say I have a variable nested deeply within a massive object which I re-use quite often: ``` i = 10000000; while (i) { i--; document.write( bigobject.a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p ); } ``` Would it be faster to cache it in a new variable outside of the loop? ``` v = bigobject.a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p ``` and use that cached variable in my loop? ``` document.write ( v ); ``` For the less visually oriented: Are JavaScript variables cached automatically or does the browser have to search through the larger variable each time it's requested?