鑑於這種Java代碼:Java:比較int時==操作符如何工作?
int fst = 5;
int snd = 6;
if(fst == snd)
do something;
我想知道Java將如何比較平等這種情況。它會使用XOR操作來檢查平等嗎?
鑑於這種Java代碼:Java:比較int時==操作符如何工作?
int fst = 5;
int snd = 6;
if(fst == snd)
do something;
我想知道Java將如何比較平等這種情況。它會使用XOR操作來檢查平等嗎?
你問:「這會變成什麼原生機器碼?」?如果是這樣,答案是「實施 - depdendent」。
但是,如果您想知道使用了什麼JVM bytecode,只需查看生成的.class文件(例如使用javap即可反彙編)。
+1絕對!如果沒有像「如何實現'int'平等'這樣的決定一直到JVM的編寫者,他/她可能會爲他們編寫JVM :) – dasblinkenlight 2012-07-13 21:06:36
非常感謝。我找到了我需要的東西。 – Arpssss 2012-07-13 21:11:05
值得補充的是,甚至可以看到JIT編譯器生成的本機代碼。在那裏,你終於可以見證你的XOR或CMP或任何'=='碰巧變成。 – 2012-07-13 21:46:21
如果您詢問JVM,請使用javap
程序。
public class A {
public static void main(String[] args) {
int a = 5;
System.out.println(5 == a);
}
}
這裏是拆解:
public class A {
public A();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_5
1: istore_1
2: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
5: iconst_5
6: iload_1
7: if_icmpne 14
10: iconst_1
11: goto 15
14: iconst_0
15: invokevirtual #3 // Method java/io/PrintStream.println:(Z)V
18: return
}
在這種情況下,它優化了支化位和使用if_icmpne
。在大多數情況下,它將使用if_icmpne
或if_icmpeq
。
if_icmpeq
:if ints are equal, branch to instruction at branchoffset (signed short constructed from unsigned bytes branchbyte1 << 8 + branchbyte2)
if_icmpn
:if ints are not equal, branch to instruction at branchoffset (signed short constructed from unsigned bytes branchbyte1 << 8 + branchbyte2)
不,這將執行'if_icmpeq' JVM字節碼指令。 – jn1kk 2012-07-13 21:03:50
@jsn這聽起來像是一個很好的答案(嗯,或許有點擴大了)。 – 2012-07-13 21:05:00
'=='操作轉換爲字節碼中的'if_icmpeq'指令;在執行過程中,這會從操作數堆棧中彈出對象引用並對它們進行比較。 – Lion 2012-07-13 21:16:20