After 2 weeks working with Java2d, here are some little tricks to help optimize your code
Don’t create too many intermediate Graphics
Creating a Graphics is quite long, and usually it’s not the good way to do stuff.
You should try to think all your rendering process with the less Graphics object creation (getGraphics, createGraphics,…), if you can just use the one given by the paint method (or the one from your double buffering system), and pass it as argument in all your rendering functions to directly draw on it.
Try to stick to environment image format
If the display image format is not the same as your application, rendering can be very slow, usually to create an image you should just use the createCompatibleImage function
public static BufferedImage createCompatibleImage(int width, int height, boolean transparent)
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
BufferedImage ret = gc.createCompatibleImage(width, height, transparent ? Transparency.TRANSLUCENT : Transparency.OPAQUE);
Don’t use transparency when it’s not needed
Operations with image using transparency take more time than without, try not to use transparency when it’s not needed. I’m sure you can find some places where it’s not useful : your screen is not transparent, so a few things could certainly be rendered with no transparency…
Use the correct environment variables
On my Linux system I had a very low frame-rate (~ 20fps), and was quite disappointed, but it was just due to a VM parameter, when I set it, the frame rate increased to ~200fps :
I don’t really understand why this parameter changed so much the frame rate, help and other parameters can be found on the oracle website : http://download.oracle.com/javase/1.5.0/docs/guide/2d/flags.html
That’s all for this tips and tricks post, if I find other useful stuffs, I will make other posts.