I've been looking over some JavaScript code that is designed to be run in a performance-sensitive environment, mainly a game engine in mobile environments.
In many cases this code doesn't use local variables but instead prefers to use explicit chains, e.g.
if (this.x.y[z].i) {
this.x.y[z].a += this.x.y[z].b;
}
Where both this.x.y
and this.x.y.z
represent "duplication" - and where none of the intermediate properties have getters, and where q
is a local variable not used elsewhere - can be treated semantically equivalent to the following.
var q = this.x.y[z]
if (q.i) {
q.a += q.b;
}
(The names have been kept vague particularly to try and mitigate bias; this question is not about which "pattern" to follow - although I do prefer the latter and intend to use it 100% and thus am asking this question.)
Now, before I get a whole slew of comments talking about "write code for clarity" and "don't prematurely optimize", keep reading!
So given the following assertions/axiom and noting that this question is not about how to improve performance, but rather if using local cache/"alias" variables can decrease performance on relevant JavaScript implementations:
Can/will using local variables instead of [multiple] direct property access result in a decrease in performance? Where such a decrease is "non-negligible.."
The answer probably depends more on the browser than the code. Consider that JavaScript was created to be "interpreted", meaning the code is parsed and executed as it is parsed. In that scenario the declaration of a local variable gets parsed and executed every time the function is called, containing that variable-declaration. That can't qualify as "fast".
However, modern JavaScript-processing engines are not doing things that way any more; they are essentially compiling the code when the web page loads. The declaration of a local variable now gets processed once --along with declarations of all other variables, such as globals and object-properties. In this scenario it is likely that there isn't a fastest way of variable declaration, for the person writing the code to prefer to use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With