...

View Full Version : optimising a loop through a table



Kirl
08-02-2006, 07:05 PM
I have been working on a javascript snake version and most of the functionality is there, but I found that one loop in particular is really slowing down the program.

If I delete this one loop, everything runs smoothly again. This particular loop resets all table cell BG's to white, except for the randomly placed red cell (wich is the cell that makes the snake grow).

This loop is repeated at every interval of the program. So, everytime the snake moves a square, it loops through all table cells. This doesn't seem very economic, but it worked well (a smaller table didn't cause any noticable slowdown). When trying larger size's, it becomes apparant.


// clear cells
for ( tr = 1; tr < tableSize; tr++ ) // 5 rows of 5 cells
{
for (tc = 1; tc < tableSize; tc++ ) // 5 collums (1 row)
{
cellBG = getObject( [tr] + [tc] );
if ( cellBG.style.backgroundColor != "red" )
{
cellBG.style.backgroundColor = "white";
//cellBG.innerHTML = "";
}
}
}

Is there any way to reduce the work it has to do, to set all cell BG's to white?

You can find the full code here (http://www.kirl.nl/javaSnake.html?). To change the nr of tables cells, you can set the tableSize variable (some slight weirdness when > 10 but I know how to fix that).

TNO
08-07-2006, 09:50 PM
Instead of updating individual color properties, keeping track of colors and changing them through a stylesheet may be faster. Use javascript to update the class of the element(s), and you should see a significant improvement.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum