14.3. Memory

One aspect of performance tuning is making your application handle memory nicely. It's very awkward for your support staff if the only answer they have for some problems is "buy more memory." An ideal application doesn't use much memory and doesn't crash if it can't get enough memory.

In 2D applications, images are the biggest area of concern for memory usage. If your application does any image handling, including double-buffered drawing, you should probably be thinking about memory.

14.3.1. Images

Any image in your application uses some memory. The formula is pretty simple:

memoryUsed = width · height · bytesPerPixel

This formula gives you a minimum size for the image. Of course, there's some additional memory for the Image or BufferedImage object itself, but this is small compared to the raw image data. The actual memory used also depends on how the image data is stored. Suppose you had an image with a 16-color palette. Each pixel can be represented with four bits. An inefficient way to store this image would be to put the four bits of each pixel into an 8-bit byte. In this case, the image data would actually occupy twice as much memory as given in the formula above.

The following method calculates the memory usage for a BufferedImage. It retrieves the actual DataBuffer for the image and calculates the size accordingly. Note that this calculates the full size of the image's data buffers, which is a little more realistic measure of memory usage than the minimum ...

Get Java 2D Graphics now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.