I was creating a simple game and was shocked to see how the performance started to degrade. It never happened to me before, most probably because I use images and not the context drawings. So I used this function and the whole game becomes so slow, it just cannot be played after 30 seconds.
Office.prototype.draw = function(){
for(var i = 0; i < this.tables.length; i++){
for(var j = 0; j < this.tables[i].length; j++){
Canvas2D.ctx.rect((373 * j) + 75, (370 * i) + 250, 170, 20);
Canvas2D.ctx.fillStyle = 'green';
Canvas2D.ctx.fillRect((373 * j) + 75, (370 * i) + 250,
this.moneyBar[(i*4)+j], 20);
// Draw the experience bar.
Canvas2D.ctx.rect((373 * j) + 75, (370 * i) + 270, 170, 20);
Canvas2D.ctx.fillStyle = 'yellow';
Canvas2D.ctx.fillRect((373 * j) + 75, (370 * i) + 270,
this.expBar[(i*4)+j], 20);
// Draw the tables.
Canvas2D.drawImage(sprites.items[0], new Vector2(
(250 * j) + 50, (250 * i) + 200));
}
}
}
So as you can tell from the code, there is the multidimensional array table which has bars on top displaying moneyBar and expBar. If I am to use Canvas2D.ctx.stroke() inside the for loop, the game performance drops right away. Outside of the loop, it keeps up a bit, then it degrades. If I don't use stroke at all, works better, but degrades anyway. So I am really confused as to why this degrades so fast. Also am using requestAnimationFrame and have used the same engine in previous games and performance never degraded.
If I was to remove fillStyle, keeps up 3-4 seconds more. There are 8 tables in all, which means the for loops run 8 times per draw.
Vector2 function.
function Vector2(x, y) {
this.x = typeof x !== 'undefined' ? x : 0;
this.y = typeof y !== 'undefined' ? y : 0;
}
var ctx=Canvas2D.ctx
). The slowdown might be related to the garbage collector : try to create only one Vector2 and reuse it in your for loops. \$\endgroup\$moneyBar
and 8expBar
.this.moneyBar
andthis.expBar
are arrays, not functions. \$\endgroup\$