I am optimizing an HTML5 canvas animation.
The structure looks like this:
Animation = {
//Cache constant variables
cache : {
var1 : 1,
var2 : 2,
var3 : 3
},
render : function(){
//render to canvas
}
}
Within the render function I am calling this.cache.var1, this.cache.var2 etc… multiple times throughout and performing various calculations on them.
What I want to know is if calling this repeatedly during a single loop carries significant overhead, if so how best to optimize this?
Should I simply store a local copy within the render loop (self=this;) and work from self, Should I look at minimizing the various repeated calculations, breaking them down into various parts, storing them as local variable within the loops and work from those?
Any opinions are welcome.
Note: I am aware this might be considered micro-optimization but when dealing with heavy animation processing I really would like to squeeze every last drop I can get.
Thanks in advance.
You don’t want opinions, you want hard data! 🙂 To whit:
http://jsperf.com/this-versus-closure
Using a closure is slightly faster on Chrome, twice as slow on Firefox, about the same on IE9. Caching the reference to
this.cacheasvar cache=this.cacheimproves speed ever-so-slightly on some browsers. However, the speed differences are not noticeable enough to make a noticeable impact in any code you’re writing. As shown in the results, my tests were running at hundreds of millions of lookups per second (50 million operations/second * 3 lookups per operation), much of that possibly dwarfed by the overhead of the function call.Focus on your canvas drawing and any looping algorithms, not individual lines of code.