Optimising Java Code

The Golden Rule Of Optimisation

Don’t do it. Unless you’re an expert, in which case Don’t do it yet


Most low-level optimisations, such as replacing constants with literals, will be handled by the compiler. Similarly there’s not much point in playing around with changing such lines as x = x +1; to x++; – the compiler will deal with this.

Garbage collection

Creating/Clearing up Instances

One of the most expensive (CPU) operations is making and clearing up instances. Where there are likely to be large numbers of instances being created and then left for collection, consider using a pool or an array.

Easy things to look for are string processing routines; remember strings are immutable, so any statement that looks like a change to a string is likely to involve intermediate creations. For example, here is code that builds up spaces for indentation:

   public String indentString(int indentIndex)
       String s = "";
       while (s.length() < indentIndex * 3)
           s = s + " ";
       return s;

This creates a very large number of temporary strings, so you might think about doing things differently, for example by using StringBuffer. But remember the golden rule above. Using StringBufferin all circumstances just gives you nastier code, and can even prevent the optimiser from doing its bit…

Other things can become important in long tight loops. For example:

   Integer i = new Integer("12");
   j = j + i.intValue();

creates an intermediate Integer object. Use the class parse method instead:

   j = j + Integer.parseInt("12);

Collecting at the right time

You can ‘encourage’ the garbage collector to run, if you have ‘slack’ moments in your application, by calling


(AstroGrid 2006)


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: