沒有性能上的差異被發現。 bytecode包含相同的指令,以相同的順序操作相同的數據。
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
與
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
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() {}
}
與
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() {}
}
的各種問題重複: http://stackoverflow.com/q/7921359/143897 http://stackoverflow.com/q/1370865/143897 – 2012-01-13 07:33:58
@JayD的問題是相關的,但他們不重複IFAICS。但我會投票給一個非建設性的問題... – 2012-01-13 07:40:26
這個問題是不可能回答的,因爲它高度依賴於編譯器的實現細節。此外,差異很小,因此不值得花時間去擔心這一點。 – Jesper 2012-01-13 08:26:54