Java中的内联

2022-01-16 00:00:00 jvm java inlining inline-method

在 C++ 中,我可以声明一个内联"方法,编译器很可能会内联它.据我了解,Java 中没有这样的关键字.

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.

如果 JVM 决定这样做,内联是否完成?我能以某种方式影响这个决定吗?

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

推荐答案

其他几个答案表明只有 final 方法可以内联 - 这不是真的,因为 HotSpot 足够聪明,可以内联非final 方法,只要它们还没有被覆盖.当加载一个覆盖该方法的类时,它可以撤消其优化.显然,使方法最终意味着永远不需要......

A couple of the other answers have suggested that only final methods can be inlined - this is not true, as HotSpot is smart enough to be able to inline non-final methods so long as they haven't been overridden yet. When a class is loaded which overrides the method, it can undo its optimisation. Obviously making the method final mean that's never required...

基本上让 JVM 完成它的工作 - 它在确定内联位置方面可能比你要好得多.

Basically let the JVM do its job - it's likely to be a lot better at working out where to inline than you are.

您是否有过确信 JVM 做得不好的情况?假设您使用的是 HotSpot,您是否尝试过使用服务器版本而不是客户端?这可以产生巨大的差异.

Do you have a situation where you're convinced that the JVM isn't doing a good job? Assuming you're using HotSpot, have you tried using the server version instead of client? That can make a huge difference.

相关文章