I have an array which is part of a small JS game I am working on I need to check (as often as reasonable) that each of the elements in the array haven’t left the “stage” or “playground”, so I can remove them and save the script load
I have coded the below and was wondering if anyone knew a faster/more efficient way to calculate this. This is run every 50ms (it deals with the movement).
Where bots[i][1] is movement in X and bots[i][2] is movement in Y (mutually exclusive).
for (var i in bots) {
var left = parseInt($("#" + i).css("left"));
var top = parseInt($("#" + i).css("top"));
var nextleft = left + bots[i][1];
var nexttop = top + bots[i][2];
if(bots[i][1]>0&&nextleft>=PLAYGROUND_WIDTH) { remove_bot(i); }
else if(bots[i][1]<0&&nextleft<=-GRID_SIZE) { remove_bot(i); }
else if(bots[i][2]>0&&nexttop>=PLAYGROUND_HEIGHT) { remove_bot(i); }
else if(bots[i][2]<0&&nexttop<=-GRID_SIZE) { remove_bot(i); }
else {
//alert(nextleft + ":" + nexttop);
$("#" + i).css("left", ""+(nextleft)+"px");
$("#" + i).css("top", ""+(nexttop)+"px");
}
}
On a similar note the remove_bot(i); function is as below, is this correct (I can’t splice as it changes all the ID’s of the elements in the array.
function remove_bot(i) {
$("#" + i).remove();
bots[i] = false;
}
Many thanks for any advice given!
Cache
$("#" + i)in a variable; each time you do this, a new jQuery object is being created.Cache
bots[i]in a variable:Store (cache) the jQuery object of the DOM element within the bot representation. At the moment it’s been created every 50ms.
What I mean by this is that for every iteration of the loop, you’re doing
$('#' + i). Every time you call this, jQuery is building a jQuery object of the DOM element. This is far from trivial compared to other aspects of JS. DOM traversal/ manipulation is by far the slowest area of JavaScript.As the result of
$('#' + i)never changes for each bot, why not store the result within the bot? This way$('#' + i)gets executed once, instead of every 50ms.In my example below, I’ve stored this reference in the
elementattribute of my Bot objects, but you can add it your bot (i.e inbots[i][3])Store (cache) the position of the DOM element representing the bot within the bot representation, so the CSS position doesn’t have to be calculated all the time.
On a side note,
for (.. in ..)should be strictly used for iterating over objects, not arrays. Arrays should be iterated over usingfor (..;..;..)Variables are extremely cheap in JavaScript; abuse them.
Here’s an implementation I’d choose, which incorporates the suggestions I’ve made: