I have a loop that gets called through a window.setInterval every 30 millsec.
it looks like this:
var loop = function (w, t){
for( i=0; i<w; i++){
value= something*t;
ctx.strokeStyle="rgba(" + Math.floor(color[0]*value) + "," + Math.floor(color[1]*value) + "," + Math.floor(color[2]*value) + "," + 255 + ")";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(i ,0);
ctx.lineTo(i ,h);
ctx.closePath();
ctx.stroke();
}
}
var color =[0,0,0];
var myLoop=window.setInterval(function(){
loop(width, time);
}, 30);
For reference w is usually ~ 1000-1500
When I run this on a computer I have no problems at all. However, running on a device with less memory the program runs very slowly (ie. it draws to the canvas slowly).
I figure I have some memory leak somewhere, but I don't see where.
Alternatively, I could be crazy and allocating 1000 canvas paths is way too many. But I can't find an explanation of how the canvas drawing methods allocate memory.
Any hints?
In the example you have given here there are several issues:
i, h, time, something
are not defined. All variables that are not defined with var makes the window object dirty. Always declare all variables explicitly.
You don't need to use rgba when alpha channel = 255, just use rgb.
You can use fillStyle instead so you can use fillRect instead - this will do the same as moveTo + lineTo but this one is more semantic:
ctx.fillRect(i, 0, i + 1 , h);
And there is no need to use closePath() here as you are only drawing a line (nothing to close it with - it will just create another line on top of itself going from last point back to start so you are basically stroking double unless this is optimized for internally by the browser).
Use requestAnimationFrame (rAF) instead of setInterval. With the latter you risk stacking call and it doesn't sync to monitor vblank as rAF does (and rAF is more efficient).. In worst case use setTimeout instead.
You can also use value|0 instead of Math.floor.
Update - I forgot to also mention that Garbage Collection will have difficulties kicking in while you're in a busy loop. So for mobile devices optimizations become more important as the CPU on those is not so capable as does on a desktop computer - optimized code leave some time to breath so-to-speak.
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