今天研讀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