Inlining of method calls in JVM
Was listening to one of the Oracle TechCasts today: Towards a Universal VM. The talk was surrounded on the different capabilities of JVM. And there was a mention about inlining methods in JVM. So I’ve decided to write a small test to see how does inlining influence the performance. Test simply concatenates two strings.
So I’ve looked at three variants here:
- Direct concatenation. Something like
val1 + val2
which’s replaced with StringBuilder#append underneath by the compiler. - Static method invocation. Something like:
obj.doSomething(val1, val2) - Reflection method invocation. Something like:
method.invoke(obj, val1, val2)
Inlining of the methods is enabled in Sun JVM by default and can be disabled by passing -XX:-Inline parameter to the JVM. So below you can find the results of invoking concatenation of two string for 1000000 times:
Inline Enabled | Inline Disabled | |||||
Direct | Method | Reflection | Direct | Method | Reflection | |
Attempt 1 | 1427 | 1360 | 1465 | 1929 | 2014 | 2437 |
Attempt 2 | 1471 | 1547 | 1581 | 1959 | 2093 | 2477 |
Attempt 3 | 1440 | 1485 | 1425 | 1993 | 2067 | 2381 |
Attempt 4 | 1619 | 1495 | 1507 | 2030 | 2114 | 2515 |
Attempt 5 | 1399 | 1495 | 1530 | 2021 | 2084 | 2401 |
Average | 1471.2 | 1476.4 | 1501.6 | 1986.4 | 2074.4 | 2442.2 |
As you can see – the results are the following:
- Using internal inlining of the methods definitely makes JVM faster.
- Overhead of invoking methods is really small in comparison to the using some code directly
- Invoking method through a reflection is really small in case of inlining, less than 2%. However it’s about 18% in case of the disabled inlining.
In general it’s possible to say that modern JVMs enable inlining by default and it really makes your Java code running faster. Also it seems like inlining of the methods makes reflection method invocation work really fast and you don’t need to afraid of the reflection any more..