Method inlining with the final keyword in java

February 12th, 2009 | Tags: ,

I have noticed a lot of people on the internet asking about method inlining. The term generally arises whenever the final keyword is discussed. Basically, it is said that compilers inline methods which are declared final thereby avoiding the cost of putting them on the stack etc and thus improving performance drastically under heavy load conditions. The same is true for variables as well, their values are inlined thereby avoiding the cost of performing lookups at runtime. What nobody talks about is what exactly is inlining.

Consider the following class :

public class Inline {

	private int	i;

	public void methodA() {
		methodB();
	}

	public final void methodB() {
		i++;
                i--;
	}
}

methodB() is marked final in this case. It cannot be overriden. The compiler sees this and decides to alter the byte code of methodA() to instead look like this :

public void methodA() {
		i++;
		i--;
	}

methodB() has now been inlined into methodA() to save the cost of pushing a method onto the stack. This invocation will work faster than the earlier one although its almost impossible to determine how much faster without a proper production environment. It’s also important to note that java code is first compiled into byte code and then into runtime code by the JVM. This change of code takes place in the JVM and not during compilation. If you open your class file you will see nothing different in it from the source file.

final variables work in the same way except calls to them are replaced by their actual values because those are not going to change once they’re initialized.

It’s been said that the newer VM’s (ever since Hotspot) no longer provide benefits of marking methods and variables final as they deduce and mark them final on their own during runtime.

Share and Enjoy:
  • del.icio.us
  • Google Bookmarks
  • DZone
  • Reddit
  • Digg
  • Facebook
  • Netvibes
  • StumbleUpon
  • Technorati
  • LinkedIn
  • MySpace
  • Print
  • Slashdot
  • Share/Bookmark
  1. Hema
    November 3rd, 2009 at 11:42
    Reply | Quote | #1

    A good article on inlining