use*_*309 1 java performance bytecode
哪个表现更好?
我没有经过测试就问了这个问题因为我很懒.现在经过测试,它显示getMethod比.field略快
Integer xj = x.getJ();`
Run Code Online (Sandbox Code Playgroud)
要么
Integer yj = x.j;
Run Code Online (Sandbox Code Playgroud)
这是我编译后的java字节码
L5 {
aload1
invokevirtual testj/ByteCodeTest getJ(()Ljava/lang/Integer;);
astore4
}
L6 {
aload1
getfield testj/ByteCodeTest.j:java.lang.Integer
astore5
}
Run Code Online (Sandbox Code Playgroud)
这是我正在测试的代码:
public void setPoint(){
point=System.currentTimeMillis();
System.out.println("point"+point);
}
public void comparePoint(){
long endPoint=System.currentTimeMillis();
System.out.println("endPoint"+endPoint);
System.out.println("inteval"+(endPoint-point));
}
int count =2000000000;
public void test22(){
ByteCodeTest x = new ByteCodeTest();
setPoint();
for(int i=0;i<count;i++){
int yy= x.i+1;
}
comparePoint();
setPoint();
for(int i=0;i<count;i++){
int yy=x.getI()+1;
}
comparePoint();
}
Run Code Online (Sandbox Code Playgroud)
这是代码输出:
point1490454906205
endPoint1490454907447
inteval1242
point1490454907448
endPoint1490454908666
inteval1218
Run Code Online (Sandbox Code Playgroud)
这意味着getMethod比.field略快
字段访问比方法调用更快,但除非您在紧密循环中编写极其性能敏感的代码,否则使用一个而不是另一个的决定是设计,而不是性能.
将JIT添加到混合中,您可能无法从直接字段访问中获得任何优势.