How-to speed-up your java code myths

In my last post I covered tips that I  have collected trough out the years on how to speed up your java code,

After reviewing the tips and reading my friends criticism, I updated the list and created a new list of myths, here it is:

final: developers might think that final methods are more efficient due to the fact that the compiler will be able to inline those methods. it’s false, imagine that you are compiling the class Main with the class Inline, the non static method Main.main() creates an instance of Inline and invokes the method inline.finalMethod() which is final. on compile time everything looks great, yet in runtime we might use a different version of the compiled Inline class whereas the finalMethod is not final and can be overwritten….

Synchronization blocks: old VMs used to pay a lot of overhead for running a synchronized method, new VMs mostly knows how to trace a synchronized method that is not running concurrently and treat it as a non-synchronized one.

Calling the garbage collection manually: calling the garbage collector manually (System.gc()) is usually a mistake, the new VMs garbage collection mechanism are state-of-the-art and most likely it will invoke the GC on a better timing. moreover manual GC triggers a full collection of all generations -> that’s not a smart move.

Object pooling: allocating object on the heap is not cheep but for non-complex objects it’s not that expensive as well, design an object-pooling for simple object will cause an over-head of managing the pool  in many cases.

In general it seems like performance tips should always be revisited since new compilers and VMs try to solve exactly those problems.

Immutable objects: in general immutable objects has many advantages (1) automate thread-safety (2) their hashCode value is cacheable (3) easy to work with

a quote from Effective Java: “Classes should be immutable unless there’s a very good reason to make them mutable……..If a class cannot be made immutable, limit its mutability as much as possible.”


Leave a Reply

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

You are commenting using your 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 )

Google+ photo

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

Connecting to %s