Java 2D Drawing Optimal Performance

Zarkonnen picture Zarkonnen · Sep 29, 2008 · Viewed 40.7k times · Source

I'm in the process of writing a Java 2D game. I'm using the built-in Java 2D drawing libraries, drawing on a Graphics2D I acquire from a BufferStrategy from a Canvas in a JFrame (which is sometimes full-screened). The BufferStrategy is double-buffered. Repainting is done actively, via a timer. I'm having some performance issues though, especially on Linux.

And Java2D has so very many ways of creating graphics buffers and drawing graphics that I just don't know if I'm doing the right thing. I've been experimenting with graphics2d.getDeviceConfiguration().createCompatibleVolatileImage, which looks promising, but I have no real proof it it's going to be any faster if I switch the drawing code to that.

In your experience, what is the fastest way to render 2D graphics onto the screen in Java 1.5+? Note that the game is quite far ahead, so I don't want to switch to a completely different method of drawing, like OpenGL or a game engine. I basically want to know how to get the fastest way of using a Graphics2D object to draw stuff to the screen.

Answer

Zarkonnen picture Zarkonnen · Oct 14, 2008

A synthesis of the answers to this post, the answers to Consty's, and my own research:

What works:

  • Use GraphicsConfiguration.createCompatibleImage to create images compatible with what you're drawing on. This is absolutely essential!
  • Use double-buffered drawing via Canvas.createBufferStrategy.
  • Use -Dsun.java2d.opengl=True where available to speed up drawing.
  • Avoid using transforms for scaling. Instead, cache scaled versions of the images you are going to use.
  • Avoid translucent images! Bitmasked images are fine, but translucency is very expensive in Java2D.

In my tests, using these methods, I got a speed increase of 10x - 15x, making proper Java 2D graphics a possibility.