When Short Methods Pay Off: JIT Inlining

Among all Just-In-Time Java compiler optimizations, inlining methods is one of the most powerful one. When we usually write code following good object-oriented practices, we end up having lots of small objects with well-encapsulated attributes – most of the them accessible via getters. There is an overhead of making additional calls and increasing a callstack. Fortunately, with JIT inlining we can follow good practices and benefit from performant code.

 

A method is eligible for inlining if:

  • it’s small – the bytecode size is smaller than 35 bytes (can be overridden by -XX:MaxInlineSize=X flag)
  • it’s called frequently (it’s hot) and it’s smaller than 325 bytes (can be overridden by -XX:MaxFreqInlineSize=X flag)

 

Consider the following snippet:

 

When inlining is applied, the position.setX(x + 1) operation will look like this:

 

To make sure that a particular piece of code is inlined, you can use -XX:+PrintInlining flag (together with -XX:+PrintCompilation and -XX:+UnlockDiagnosticVMOptions):

java -XX:+PrintCompilation -XX:+UnlockDiagnosticVMOptions -XX:+PrintInlining com.performantcode.JitInlining

 

The result will be something like that:

111   19 %     4       com.performantcode.JitInlining::main @ 12 (47 bytes)

                      @ 19   com.performantcode.Position::getX (5 bytes)   accessor

                      @ 27   com.performantcode.Position::setX (6 bytes)   inline (hot)

Please notice that inline (hot) is displayed next to setX.

Leave a Reply

Your email address will not be published. Required fields are marked *