I’m making a game in HTML5’s Canvas + JavaScript. My CPU use for the tab keeps growing by a couple percent every second until it hits 50% (all of one core). I am successfully removing my objects from the array of objects, but the objects themselves seem to persist. I have tried “delete obj” and “obj = null” in a few places, but no luck.
Any ideas?
var falling_blocks = setInterval(add_falling_block, 1000);
...
function add_falling_block(){
b = new Object();
b.x = (randFromTo(0,sq) * scale) - boff;
b.y = -scale + boff;
b.color = "#f00";
b.moving = true;
b.number = f.length;
f.push(b);
}
function draw_falling_blocks(){
var db = new Array()
for(i = 0; i < f.length; i++){
var ba = f[i];
if(ba.y < (bottom + scale)){
ba.y += scale;
draw_block(ba.x,ba.y,"#f00");
}
else if(ba.y = (bottom + scale)){
db.push(i);
console.log(f.length);
}
}
for(i = 0; i < db.length; i++){
f.splice(db[i],1);
}
}
As I mentioned in my comment, CPU usage
!=memory usage. With Chrome’s developer tools, it’s easy to profile your application in order to locate the code which is consuming all of the CPU cycles.Open your app, open the dev tools, and go to the Profiles tab. Click the Record button (the black circle). It will turn red; Chrome is now recording CPU usage. Let it record for a few seconds and click the Record button again. You will now see CPU usage by function.
In this case, we can see that
draw_grid()has consumed 92% of CPU time – we’ve found our culprit!I made some changes to the
draw_gridfunction:CPU usage never tops 5% now.
A few notes:
beginPath()andclosePath()and movedstroke()into each loop iteration.strokeStyleonce. It remains the same unless you change it again.varin your loops’ initializer to restrict the variable’s (iandjin this case) scope to the local function. Otherwise, you’re creating a global variable, which is a bad idea for a variety of reasons.