Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Jan 2006
    Posts
    243
    Thanks
    14
    Thanked 2 Times in 2 Posts

    optimising a loop through a table

    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.

    Code:
    	// 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. 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).

  • #2
    TNO
    TNO is offline
    Regular Coder
    Join Date
    Apr 2005
    Posts
    213
    Thanks
    2
    Thanked 1 Time in 1 Post
    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.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •