I was looking at some JavaScript code that is designed to work in a performance sensitive environment, mainly a game engine in mobile environments.
In many cases, this code does not use local variables, but instead prefers to use explicit chains, for example.
if (this.xy[z].i) { this.xy[z].a += this.xy[z].b; }
If both this.xy and this.xyz are "duplication" - and where neither of the intermediate properties has getters, and where q is a local variable not used elsewhere - you can handle it semantically equivalent to the following.
var q = this.xy[z] if (qi) { qa += qb; }
(The names were confused, especially in order to try to soften the bias, this question does not concern which "template" should be adhered to, although I prefer it and intend to use it 100%, and therefore I ask this question).
Now, before I get a whole bunch of comments about “writing code for clarity” and “don't optimize ahead of schedule,” keep reading!
So, given the following statements / axiom and noting that this question is not about how to improve performance, but rather, if using local cache / "alias" variables can reduce performance in the respective JavaScript implementations:
- Representing a local variable with multiple member access will result in clearer code. (This is subjective, but an axiom for the question.)
- Using a local variable, as shown, for non-dynamic properties will always have the same semantics.
- Local variables are not closed; as such, there is no need to increase the lifetime of an object or otherwise hold a large area of the execution context.
- The focus is in mobile browsers, including non-low-JIT versions - for example. JavaScriptCore and / or something else was on Android prior to V8.
- Browsers are already well optimized for this case, and it is not expected that the use of local variables will lead to a noticeable increase in "performance" - this question will be the opposite.
Can / will use local variables instead of [multiple] direct access to properties, will lead to performance degradation? Where such a reduction is “non-material”.
source share