Extreme Java When vanilla Java is not enough

13Aug/080

Java2D Optimization (a.k.a "Java is NOT slow")

Playing around with Java2D, I created a little application that paints a lot of PNG images on screen (about 200). I use ImageIO to load them, but the first prototype was VERY slow (3fps maximum).

After reading about fullscreen exclusive mode API and some tips on graphics performance, I've created a BufferStrategy using the same snippet from its API. I got no improvement, but the code became a lot cleaner.

Then, I remembered my ancient days as a C programmer, where I always need to convert the image color format to the screen color format. Since I'm programming in Java, I created this snippet:

private static BufferedImage createCompatibleImage(BufferedImage img,
    boolean translucent) {
  GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
  GraphicsDevice d = e.getDefaultScreenDevice();
  GraphicsConfiguration c = d.getDefaultConfiguration();
  int t = translucent ? Transparency.TRANSLUCENT : Transparency.BITMASK;
 
  BufferedImage ret = c.createCompatibleImage(img.getWidth(),
    img.getHeight(), t);
 
  Graphics2D g = ret.createGraphics();
  g.drawImage(img, 0, 0, null);
  g.dispose();
  return ret;
}

Maybe there's a better way to copy the image, but the important part is to create an image with GraphicsConfiguration.

After this little trick, I got an impressive speed boost: from the 2fps-slow-motion-turtle to ludicrous 170fps (yes, one hundred seventy). I feel like saying: "It's over nine thousand!"