什么在java中会更有效率?If-return-else或If-return?

For*_*rce 1 java performance

我只是想知道,编译器使用什么实际上更有效

if (condition) {
    return something;
} else {
    dosomething();      
}
Run Code Online (Sandbox Code Playgroud)

要么

if (condition) {
    return something;
}
dosomething();
Run Code Online (Sandbox Code Playgroud)

我知道这些是非常低的差异,应该选择更易读的版本,但是我们只能说我们将执行这个代码十亿次,哪一个会更有效?

我也知道在"现实世界"中根本没有任何收获,但我只是好奇.

Mik*_*ark 6

没有性能差异.该字节码包含了相同的指令,以相同的顺序,在相同的数据进行操作.

   L0
    LINENUMBER 11 L0
    ICONST_1
    ISTORE 0
   L1
    LINENUMBER 12 L1
    ILOAD 0
    IFEQ L2
   L3
    LINENUMBER 13 L3
    GETSTATIC p/A.something : Ljava/lang/Object;
    ARETURN
   L2
    LINENUMBER 15 L2
   FRAME APPEND [I]
    INVOKESTATIC p/A.dosomething()V
   L4
    LINENUMBER 17 L4
    ACONST_NULL
    ARETURN
   L5
    LOCALVARIABLE condition Z L1 L5 0
    MAXSTACK = 1
    MAXLOCALS = 1
Run Code Online (Sandbox Code Playgroud)

   L0
    LINENUMBER 7 L0
    ICONST_1
    ISTORE 0
   L1
    LINENUMBER 8 L1
    ILOAD 0
    IFEQ L2
   L3
    LINENUMBER 9 L3
    GETSTATIC p/B.something : Ljava/lang/Object;
    ARETURN
   L2
    LINENUMBER 11 L2
   FRAME APPEND [I]
    INVOKESTATIC p/B.dosomething()V
   L4
    LINENUMBER 12 L4
    ACONST_NULL
    ARETURN
   L5
    LOCALVARIABLE condition Z L1 L5 0
    MAXSTACK = 1
    MAXLOCALS = 1
Run Code Online (Sandbox Code Playgroud)
public class A {
    static Object something = new Object();
    public static void main(String[] args) { 
        test(); 
    }
    private static Object test() {
        boolean condition = true;
        if (condition) {
            return something;
        } else {
            dosomething();
        }
        return null;
    }
    private static void dosomething() {}
}
Run Code Online (Sandbox Code Playgroud)

public class B {
    static Object something = new Object();
    public static void main(String[] args) { 
        test(); 
    }
    private static Object test() {
        boolean condition = true;
        if (condition) { 
            return something; 
        }
        dosomething();
        return null;
    }
    private static void dosomething() {}
}
Run Code Online (Sandbox Code Playgroud)