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