Is It Better To Use Temporary Variables In Place Of Repeated Full References?
Solution 1:
In the wonderful realm of pedantry, you are going to pay the penalty of resolving those references, time and again.
If these were "classes" (constructed objects, which might be referencing values on the proto chain), then you pay the added penalty of failing to find the value on the object, and ascending the proto chain until you do (or hit Object.prototype, still miss the property, and throw a reference error, when you try to access a property of that missing object).
Now, all told, if that added even 1ms in your stress tests of modern engines, I would be flabbergasted.
Chrome's V8 will go a long way to recompile code on the fly, which includes things like unwinding loops, inlining functions, et cetera; so long as you use functions consistently (passing similar arguments/argument-types), every time.
There were some good talks on this stuff, relating to writing game engines in Chrome, circa 2012, I believe.
The moral is that most of what you do, if done more than a couple of times, will just be compiled down to an inline operation...
...in a new browser...
You would take a performance hit the moment you did something like
if (i % 3001) { a.b.e.f.g[6]; }
else { a.b.c.d.e.f[5]; }
...again, that's modern engines.
If you were to run your load test on a 2003 Windows XP system, running IE6, your numbers should be different, due to the aforementioned reasons.
They shouldn't be hundreds of ms off... They should, however, reflect the performance hit of dereferencing values multiple times, and that performance penalty should increase if the properties are proto linked, and increase again based on the distance up the chain to resolve each property.
To wit, I'm referring to the browsers where tests of a.b.c
versus a["b"]["c"]
were perceivably different.
Solution 2:
As you yourself tested it, and as confirmed by Matt Burland above, nested object references are not meaningfully different in performance to copied references.
The thing you want to watch for in terms of performance is function calls. If you have foo.a().b().c()... instead, the function calls themselves start to become expensive. Here the difference becomes pronounced, as shown in my little revision of Matt's jsperf test: http://jsperf.com/temp-vs-dot/2
Post a Comment for "Is It Better To Use Temporary Variables In Place Of Repeated Full References?"