I have a two dimensional associative array which contains a map of blocks that need to be drawn in a html5 canvas.
It currently takes around 28ms to complete it, which is too much (I’m running the code 60 times a second), I need to run though the matrix more efficienty somehow. This is my code:
for(var x=0; x<Object.keys(matrix).length; x++){ // Run through cols
col = Object.keys(matrix)[x];
for(var y=0; y<matrix[col].length; y++){ // Run though rows
row = Object.keys(matrix[col])[y];
if(matrix[col][row] != '0'){
drawRect(col,row,blockSize,blockSize);
}
}
}
I hope it’s inefficient and something can be corrected. How can you loop the total of a 2D array most efficiently?
You must use the double for loop to loop an entire 2-D array. As with trying to speed up any code with a performance issue, the very first step is to figure out what is taking the most time and work on your optimizations in that element of the issue first.
The likely guess is that drawRect takes way more time than any of the issues in the loop, but if you want to speed up the rest of the code, you can do these things:
Object.keys(matrix)so it is not constantly recalculatedforloop so it is not re-computed every time through each loopThat code would look like this: