私有方法内联 [英] Private method inlining
问题描述
在Scala 不可变矢量代码有一条评论说:
In the Scala immutable Vector code there is a comment that says:
原则上,大多数成员应该是私人的。但是,必须谨慎选择访问权限以防止方法内联
In principle, most members should be private. However, access privileges must be carefully chosen to not prevent method inlining
- 私有对内联的影响是什么决定?
- 这是否也适用于Java?
推荐答案
这通常不适用于Java。访问检查仅在决议过程。当Java方法进行JIT编译时,符号引用已经过解析和验证。实际上,内联不是在原始字节码上执行,而是在编译器特定的中间表示上执行。因此,访问修饰符通常不具有性能副作用。
This generally does not apply to Java. The access checks are performed only once during the Resolution process. When Java method is JIT-compiled, the symbolic references are already resolved and verified. In fact, the inlining is performed not on the original bytecode, but on the compiler-specific intermediate representation. So, the access modifiers does not usually have performace side-effects.
但是,我可以编写一个人工测试用例,其中 private
/ public
修饰符会显着影响性能:
However, I can write an artificial test case where a private
/public
modifier dramatically affects the performance:
public class Test {
static final Inner inner = new Inner();
static class Inner {
int x = 1;
int getX1() { return x; }
int getX2() { return getX1(); }
int getX3() { return getX2(); }
int getX4() { return getX3(); }
int getX5() { return getX4(); }
int getX6() { return getX5(); }
int getX7() { return getX6(); }
int getX8() { return getX7(); }
int getX9() { return getX8(); }
private int getPrivate() { return getX9(); }
public int getPublic() { return getX9(); }
}
@GenerateMicroBenchmark
public int inlinePrivate() {
return inner.getPrivate();
}
@GenerateMicroBenchmark
public int inlinePublic() {
return inner.getPublic();
}
}
Benchmark Mode Thr Cnt Sec Mean Mean error Units
b.Test.inlinePrivate thrpt 1 3 5 289480,928 2247,656 ops/msec
b.Test.inlinePublic thrpt 1 3 5 1157970,245 18473,139 ops/msec
此效果用合成方法解释访问$ 000
生成 javac
以允许访问内部类的私有成员。在上面的测试用例中,这个额外的访问器阻止了内联,因为HotSpot中默认的最大内联级别是9( -XX:MaxInlineLevel = 9
)。由于 getPrivate()
无法直接从外部类调用,额外的访问$ 000()
方法使得10级调用,因此没有内联。
This effect is explained by a synthetic method access$000
which javac
generates to allow access to a private member of the inner class. In the above test case this extra accessor prevents from inlining, because the default maximum level of inlining in HotSpot is 9 (-XX:MaxInlineLevel=9
). Since getPrivate()
cannot be called directly from the outer class, the extra access$000()
method makes 10th level of invocation and therefore is not inlined.
这篇关于私有方法内联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!