HTML and CSS Reference
In-Depth Information
Listing 8-12. Improving Grid Performance
var i = 0;
for ( ; i < gridRows ; ++i ) {
for ( j = 0 ; j < gridCols ; ++j ) {
if (withinScreen()) {
if (Grid[i] === undefined) {
Grid[i] = [];
}
// Flag all the cells as "modified"
Grid[i][j] = 1;
}
}
}
While this approach might improve the performance, you will realize later what happens when the values of
gridRows and gridCols surpass 1,000,000, 100,000, or as little as 10,000. In such cases, you would quickly notice that
the real problem lies in the loops themselves, which are cycling the entire range of values between zero and
gridRows / gridCols .
From Mario Bros to Megaman, Sonic the Hedgehog, or SimCity 2000, having a performant grid-rendering
algorithm is a must-have in any game with a sufficiently large grid of values. Luckily, you have already figured out the
“hardest” part of the problem, which is how to discover which cells are dirty and should be repainted; the rest is
accounting for the missing stuff, such as the initialization loop, or how values are accessed in the rendering routine.
But let's see how you can make this even better. You're going to start by displaying a simple grid, as shown in Listing 8-13.
Listing 8-13. Displaying a Simple Grid
;(function() {
var fps = 30, // Define the maximum number of FPS
interval = 1000 / fps, // Calculate the interval in milliseconds
delta = 0, // Variable initialisation
previousTs = 0, // Variable initialisation
shouldRepaint = true, // Set the repaint flag to true by default
Grid = [], // Initialize an array where we're going to be storing the grid values
gridCols = 1000, // Setup the number of columns of the grid
gridRows = 1000, // Setup the number of rows of the grid
viewportWidth = 640, // Setup the width of the viewport (the canvas)
viewportHeight = 480, // Setup the height of the viewport (the canvas)
cellWidth = 60,
cellHeight = 30,
canvas = document.querySelector('canvas'), // Grab a reference to the canvas object...
ctx = canvas.getContext('2d'), // ...and its context
i = 0, // Declare counters for the for loop we'll be using below
j = 0; // Declare counters for the for loop we'll be using below
 
Search WWH ::




Custom Search