天天看點

java 中的while(true)和for(;;)的差別

今天研讀Handler源碼的時候發現在Looper死循環裡面對消息循環的代碼是這樣子寫的

public static void loop() {

    //獲得一個 Looper 對象
    final Looper me = myLooper();

    // 拿到 looper 對應的 mQueue 對象
    final MessageQueue queue = me.mQueue;

    //死循環監聽(如果沒有消息變化,他不會工作的) 不斷輪訓 queue 中的 Message
    for (;;) {
        // 通過 queue 的 next 方法拿到一個 Message
        Message msg = queue.next(); // might block
        //空判斷
        if (msg == null)return;
        //消息分發   
        msg.target.dispatchMessage(msg);
        //回收操作  
        msg.recycleUnchecked();
    }
}
           

循環為什麼不用While呢? for 和 while有什麼差別呢?

對比了一下兩者差別:

while

編譯前:

while (true);  
           

編譯後:

mov     eax,1 
test    eax,eax 
je      wmain+29h 
jmp     wmain+1Eh  
           

編譯前:

for(;;);
           

編譯後:

jmp     wmain+29h       
           

由上面的結果可以看出

for編譯器會優化成一條彙編指令,而while編譯器會有很多條彙編指令

結果:

for ( ; ; )指令少,不占用寄存器,而且沒有判斷、跳轉

弄明白這裡的差別,就知道Looper裡面的loop為什麼要使用for(;;)而不是while

繼續閱讀