Drawing blocks for a 2D game background This draws blocks on the screen from a grid to make a background for my game. I am wondering if anyone has any suggestions on optimizing it for speed.

int blockwidth=blocksize-2;
//Draw coloured blocks
for (int x=0;x&lt;sizex;x++){
   int screenx=-(int)camerax+(x*blocksize);
      if (screenx&gt;-blocksize &amp;&amp; screenx&lt;gamewidth){
        for (int y=0;y&lt;sizey;y++){
          int screeny=-(int)cameray+(y*blocksize);    
          if (screeny&gt;-blocksize &amp;&amp; screeny&lt;gameheight){              
            if (tiles[x][y][0]&gt;0){
                g.setColor(new Color( tiles[x][y][1]));
                //g.fillRect(screenx,screeny,blockwidth,blockwidth); 
                g.drawImage(Iloader.Imagelist.get(0), screenx,screeny, screenx+blockwidth,screeny+blockwidth, graphicsize,0,graphicsize*2,graphicsize, null);
            } else {
                //g.setColor(new Color( tiles[x][y][1]  | 0xFFFF0000));
                g.setColor(new Color( tiles[x][y][1]));
                g.fillRect(screenx,screeny,blockwidth,blockwidth);   

            }
          }
        }
    }
 }
There are a few optimizations I can see in your code.


creating a new Color every time is a little severe. You can do a few things here, for example, if your color palette is limited, then cache the individual Color instances. I know it sounds petty right now, but, when you add it up there are a lot of new Color instances created.

What you should at minimum do, is track your last Color used, and only create a new one if it is different.
Pull the Iloader.Imagelist.get(0) outside the loop, and have Image image = Iloader.Imagelist.get(0)
Pull calculations outside the loops where you can... and continue/break when you can too.

Image image = Iloader.Imagelist.get(0);
int screenx=-(int)camerax - blocksize;
for (int x = 0; x &lt; sizex; x++){
    screenx += blocksize;
    if (screenx &lt;= -blocksize) {
        continue;
    }
    if (screenx &gt;= gamewidth) {
        break;
    }
    int screeny= -(int)cameray - blocksize;
    for (int y = 0; y &lt; sizey; y++){
        screeny += blocksize;
        if (screeny &lt;= -blocksize)
            continue;
        }
        if (screeny &gt;= gameheight) {
            break;
        }              
        if (tiles[x][y][0] &gt; 0) {
            // need to set the color here? g.setColor(new Color( tiles[x][y][1]));
            g.drawImage(image, screenx, screeny, screenx + blockwidth,
                        screeny + blockwidth, graphicsize, 0, graphicsize * 2,
                        graphicsize, null);
        } else {
                //g.setColor(new Color( tiles[x][y][1]  | 0xFFFF0000));
            g.setColor(new Color( tiles[x][y][1]));
            g.fillRect(screenx,screeny,blockwidth,blockwidth);   

        }
    }
}



The above code does not have the mechanism for caching the color. You should figure one out.