Reputation: 1865
Is it worth it to hold values of this.key
in variables?
Would it have an impact on the speed when assuming I have to do this operation every frame?
Simple example:
class Vector3 {
constructor(X = 0, Y = 0, Z = 0) {
this.X = X
this.Y = Y
this.Z = Z
}
toVector2() {
return new Vector2(
(this.Y - this.X) * COS27,
-((this.Y + this.X) * SIN27 + this.Z)
)
}
}
vs
class Vector3 {
constructor(X = 0, Y = 0, Z = 0) {
this.X = X
this.Y = Y
this.Z = Z
}
toVector2() {
const {X, Y, Z} = this
return new Vector2(
(Y - X) * COS27,
-((Y + X) * SIN27 + Z)
)
}
}
Which of them is more efficient? Can garbage collection affect performance here?
Upvotes: 0
Views: 85
Reputation:
The other answers are fundamentally wrong, because they ignore optimizations done by the engine. Modern engines will generally cache this.X
if necessary so that further accesses do not involve a lookup. It is even possible that the engine could do a better job at caching than you could yourself, since it would not require extra local variables being put on and popped off the stack.
The other answers are also wrong because they do not point out that any difference in performance, to the extent it exists at all, would be in the sub-microsecond range.
The other answers are also wrong because because they do not point out that optimization should be done when and if found to be necessary by benchmarking your application.
The only reason to declare local variables as you have done in the second case is for purposes of readability and clarity.
Upvotes: 2
Reputation: 13807
This is very much micro-optimization, unless you have a performance bottleneck at property access. However just by looking at what's happening:
1.) Direct property access:
When you repeatedly access a property on any object, you will look those properties up in a hashtable like structure (which is fast), but if not found then (possibly) in the whole prototype chain (which might not be as fast).
2.) Assigning to locals:
When assigning to local variables, you do the lookup once, and work with variables in the local scope later, which is (supposed to be) faster.
Conclusion:
Second option would be more "efficient" and if it matters to you, much more readable in my opinion. Also if you repeatedly access the same properties, it makes sense to save them in locals - gets rid of a bunch of repetition and with the destructuring syntax it's really pleasant to look at.
Upvotes: 2