Inlining is an optimization performed by the Java Just-In-Time compiler.
If you have a method:
public int addPlusOne(int a, int b) {
return a + b + 1;
}
which you call like this:
public void testAddPlusOne() {
int v1 = addPlusOne(2, 5);
int v2 = addPlusOne(7, 13);
// do something with v1, v2
}
the compiler may decide to replace your function call with the body of the function, so the result would effectively look like this:
public void testAddPlusOne() {
int v1 = 2 + 5 + 1;
int v2 = 7 + 13 + 1
// do something with v1, v2
}
The compiler does this to save the overhead of actually making a function call, which would involve pushing each parameter on to the stack.
This can clearly only be done for non-virtual functions. Consider what would happen if the method was overriden in a sub class and the type of the object containing the method isn't known until runtime...how would the compiler know what code to copy: the base class's method body or the sub class's method body? Since all methods are virtual by default in Java, you can explicitly mark those which cannot be overriden as final
(or put them into a final
class). This will help the compiler figure out that method will never be overriden, and it is safe to inline. (Note that the compiler can sometimes make this determination for non-final methods as well.)
Also, note the word may in the quote. Final methods aren't guaranteed to be inlineable. There are various ways you can guarantee a method isn't capable of being inlined, but no way to force the compiler to inline. It will almost always know better than you anyway when inlining will help vs. hurt the speed of the resulting code.
See wikipedia for a good overview of benefits and problems.