我为什么要问:
我想知道编译器端是否进行了任何优化,使一种或另一种方法返回更可取。自从我读了this post python 没有优化运行速度更快的方法。
示例:
我已经声明了 2 个传递相同值的方法。但是 barA
通过内部字段声明返回它。
public class Foo {
public int barA(){
int a = 1;
return a;
}
public int barB(){
return 1;
}
}
测试:
public class TestFoo {
Foo foo = new Foo();
Method methodA = foo.getClass().getMethod("barA");
Method methodB = foo.getClass().getMethod("barB");
public TestFoo() throws NoSuchMethodException {
}
@Test
public void methodA() throws Exception {
assertTrue(Integer.TYPE.equals(methodA.getReturnType()));
}
@Test
public void methodB() throws Exception {
assertTrue(Integer.TYPE.equals(methodB.getReturnType()));
}
@Test
public void equalsSame() throws Exception{
assertEquals(foo.barA(), foo.barB());
}
}
结果:
测试表明我实际上在两种方法中处理相同的值和返回类型。
免责声明: 这张图片并不是为了突出秒表,junit 为每个方法运行,因为它与我所询问的编译器优化没有任何关系。
问题:
Java 是否真的尝试优化掉“无用的”字段声明以加快执行速度?
我找不到解决这个问题的问题。
使用:
- jdk 1.8.0_121
- 6 月 4.10
最佳答案
如果我们举个例子:
class Main {
int foo() {
int i = 0;
return i;
}
int bar() {
return 0;
}
public static void main(String[] args) {
new Main().foo();
new Main().bar();
}
}
并查看字节码:
class my.pckage.Main extends java.lang.Object{
my.pckage.Main();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
int foo();
Code:
0: iconst_0 //push zero onto the stack
1: istore_1 //pop off the stack and store in local variable
2: iload_1 //load an int value from local variable 1
3: ireturn //return an integer from a method
int bar();
Code:
0: iconst_0
1: ireturn
public static void main(java.lang.String[]) throws java.lang.Exception;
Code:
0: new #2; //class my/pckage/Main
3: dup
4: invokespecial #3; //Method "<init>":()V
7: invokevirtual #4; //Method foo:()I
10: pop
11: new #2; //class my/pckage/Main
14: dup
15: invokespecial #3; //Method "<init>":()V
18: invokevirtual #5; //Method bar:()I
21: pop
22: return
}
您可以看到它并没有在这个级别进行优化。
至于 JIT 编译器是否决定在运行时对其进行优化将取决于所针对的特定平台。
关于java - Java 是否优化掉了一个仅用作返回值的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50291656/