Inlining in Java

2019-01-04 02:26发布

In C++ I can declare a method "inline" and the compiler is likely to inline it. As far as I understand there is no such keyword in Java.

Inlining is done if the JVM decides to do so? Can I influence this decision somehow?

8条回答
对你真心纯属浪费
2楼-- · 2019-01-04 03:27

'In C++ I can declare a method "inline" and the compiler will inline it'... or not. The compiler is free to make the function inline or not and you cannot really affect the result. It is only a hint to the compiler.

In Java there is no such thing, the compiler (and later the VM while performing optimizations) can decide to 'inline' the method.

Note that final methods have greater chances of being inlined (the compiler cannot inline non-final methods, as they may be overwritten in derived classes). With modern VM, a similar optimization can be made at runtime. The VM will flag the type (so it can perform type checks) and will inline the code. Only if the check fails, it will fall back into the original unoptimized polymorphic method call.

查看更多
来,给爷笑一个
3楼-- · 2019-01-04 03:28

Although the java compiler can do inline (for short early-bound methods) the real inlining will be done by the JIT compiler. The JIT (HotSpot) compiler will be able to,even, inline virtual methods. The best way to interact with it is to write a simple and concise code. Most likely, code that uses Reflection will not allow for inlining.

Hope that helps.

查看更多
登录 后发表回答