包含私有调用的jvm Java内联方法
假设jvm将b.foo()方法标识为hot,它会尝试将其内联吗?因为如果这样做,调用指令B.bar()将内联到A.main方法中,这是禁止的,因为bar是私有的。jvm在这些情况下做什么
欢迎提供更多详细信息。谢谢
public class A {
public static void main(String[] args)
{
B b = new B();
for (int i=0; i<99999; i++)
b.foo();
}
}
class B {
public void foo() {
bar();
}
private void bar() { // do something. (is small method)
}
}
编辑:我这样问是因为当我尝试自己(用字节码)进行优化时,我得到了一个有意义的验证错误:
爪哇。lang.VerifyError:错误的invokespecial指令:当前类不可分配给引用类
编辑2:
public static void main(java.lang.String[]);
descriptor: ([Ljava/lang/String;)V
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=2, locals=5, args_size=1
0: new #13 // class B
3: dup
4: invokespecial #14 // Method B."<init>":()V
7: astore_1
8: iconst_0
9: istore_2
10: iload_2
11: ldc #15 // int 99999
13: if_icmpge 30
16: aload_1
17: astore 4
19: aload 4
21: invokespecial #18 // Method B.bar:()V // VERIFY ERROR HERE
24: iinc 2, 1
27: goto 10
30: return
StackMapTable: number_of_entries = 2
frame_type = 253 /* append */
offset_delta = 10
locals = [ class B, int ]
frame_type = 19 /* same */
LineNumberTable:
line 5: 0
line 6: 8
line 7: 16
line 14: 19
line 15: 24
line 6: 24
line 8: 30
# 1 楼答案
在Java中,优化通常在JVM级别完成。在运行时,JVM会执行一些“复杂”的分析,以确定要内联哪些方法。它在内联方面可能具有攻击性,而Hotspot JVM实际上可以内联非final方法
java编译器几乎从不内联任何方法调用(JVM在运行时完成所有这些)。它们执行内联编译时常量(例如,最终静态原语值)。但不是方法
有关更多资源:
Article: The Java HotSpot Performance Engine: Method Inlining Example
Wiki: Inlining in OpenJDK,未完全填充,但包含指向有用讨论的链接