3
\$\begingroup\$

This code draws two sets of 9 boxes on the screen to display the contents of two arrays.

How can I speed up, shorten and make the code more efficient?

    for (int x=0;x<3;x++){
        for (int y=0;y<3;y++){
            if (pattern[x][y]==1){
                g.setColor(colorrange.colb());
                g.fillRect(actlo+(x*size),actlo+(y*size),size,size);
            }
                g.setColor(Color.yellow);
                g.drawRect(actlo+(x*size),actlo+(y*size),size,size);

            if (patternb[x][y]==1){
                g.setColor(colorrange.colb());
                g.fillRect(actlo+(x*size),inlo+(y*size),size,size);
            }
                g.setColor(Color.yellow);
                g.drawRect(actlo+(x*size),inlo+(y*size),size,size);                 
        }
    }
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

Multiplies can be pretty expensive within loops, so I minimized the use of them by precalculating where possible. It is also better to have the Y loop before the X loop to prevent cache misses (which wouldn't matter on a really small array like this but is a good practice). Consider this alternative:

for(int y = 0; y < 3; y++)
{
  final int yy = y * size;

  for(int x = 0; x < 3; x++)
  {
    final int xx = x * size;

    if(pattern[x][y] == 1)
    {
      g.setColor(colorrange.colb());
      g.fillRect(actlo + xx, actlo + yy, size, size);
    }

    g.setColor(Color.yellow);
    g.drawRect(actlo + xx, actlo + yy, size, size);

    if(patternb[x][y] == 1)
    {
      g.setColor(colorrange.colb());
      g.fillRect(actlo + xx, inlo + yy, size, size);
    }

    g.setColor(Color.yellow);
    g.drawRect(actlo + xx, inlo + yy, size, size);
  }
}
\$\endgroup\$
3
  • \$\begingroup\$ Great, I hadn't thought of that... \$\endgroup\$
    – Munkybunky
    Nov 23, 2014 at 23:32
  • \$\begingroup\$ Can you expand a little on why this is better in terms of cache coherency? \$\endgroup\$
    – Nihathrael
    Nov 24, 2014 at 8:56
  • \$\begingroup\$ Corrected post (used incorrect terminology), thank you. \$\endgroup\$
    – joe_7
    Nov 24, 2014 at 12:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.