GC friendly java coding

1. Give size when initing collections

When initing Map/List etc, if we could know the size, pass into the constructor. This way JVM does not have to constantly allocate memory to new arrays when the size grows.

2. Use immutable

Immutability has a lot of benefits. One of them is typically ignored which is its effect on GC.

We cannot modify the fields/references in the immutables.

public class ObjectPair {

   private final Object first;
   private final Object second;

   public ObjectPair(Object first, Object second) {
       this.first = first;
       this.second = second;
    }

    publicObject getFirst() {
       return first;
    }

   public Object getSecond() {
       return second;
    }

}

This means immutables cannot reference objects that are created after it. This way when GC is performed in the YoungGen, it could skip the immutables in OldGen which will not have reference to the objects in the current YoungGen which means less memory page scan and result in shorter GC cycle.

3. prefer Stream to big blob

When dealing with large files, reading it to memory will generate a large object on heap and could easily result in OOM. Expose the file as Stream and do proper handling would be more efficient since typically we would have many API for processing Streams.

4. string concat in loop

Typically java compiler will do pretty good optimization for the String concats(with ‘+’) and use StringBuilder.

However when it comes to for loop, it would be a different story. The temp strings in the loop will result in a lot of new StringBuilder objects being created. So a better way is to use StringBuilder directly when it comes to concat with loop. More detail can be found in this SO answer.

Advertisements

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 )

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