Basic Java Optimisation Hints

2. Take a good look at your method call chains

General rule of thumb static methods are cheapest, then final methods, then instance methods, then interface methods and finally synchronized methods:

Methods. Great things aren't they? A lot of fun. But method calls in Java are a bit more involved than in other languages and in the wrong circumstances they can become quite expensive. How expensive? Well that depends in part on your JVM but mostly on the type of method. As a general rule of thumb static methods are cheapest, then final methods, then instance methods, then interface methods and finally synchronized methods:

static < final < instance < interface < synchronized

And the difference is not trivial: in one popular JVM interface methods take three times longer to call than static methods declared in a class. In the same JVM synchronized methods are almost seven times slower than statics!

Single method call the cost is still pretty minimal, but chaining them together mounts up the cost (methodA() calls methodB() calls methodC())

Long call chains are a common feature of Java's event model

Now for a single method call the cost is still pretty minimal. But once you start chaining them together (methodA() calls methodB() calls methodC()) the costs mount up. Long call chains are a common feature of Java's event model: "this listener registers with that component and when it receives event X it passes on event Y". This is known as delegation and it can be an elegant technique to simplify your design. However, if you delegate your event handling too much you get long call sequences. If such a sequence is called every time the user twitches the mouse, then the costs can blow right out.

Sometimes you don't have any choice about the type of method you use. If you're writing an AWT event listener you simply have to implement one of the well-defined interfaces. But for your own code you should design the shortest possible call chains for the performance critical code. The crucial design tips are: