duff's device 循环
C语言原版duff's device 循环代码
switch(count%8){ case 0: do{ *to = *from++; case 7: *to = *from++; case 6: *to = *from++; case 5: *to = *from++; case 4: *to = *from++; case 3: *to = *from++; case 2: *to = *from++; case 1: *to = *from++; }while(--n>0);
将swtich引入到了do中增加了每次循环的性能开销,原版算法中使用switch+case+do其实是利用了C语言的编译机制的"跌落"行为,
实现了switch只会在首次运行起效的功能.
将case语句置入do-while循环中,进入switch语句中时,正常的进行了case跳转,因为没有break语句,就将逐条顺序执行,
但当执行到while循环时,顺序执行do内代码,case语句就被视为了用于goto跳转的label:标记,不再起效. 这样虽然从编码的逻辑来说不太符合情理,
但是的确能提高效率!
//credit: Jeff Greenberg var iterations = Math.floor(items.length / 8), startAt = Items.length % 8, i = 0; do{ switch(startAt){ case 0: process(items[i++]); case 7: process(items[i++]); case 6: process(items[i++]); case 5: process(items[i++]); case 4: process(items[i++]); case 3: process(items[i++]); case 2: process(items[i++]); case 1: process(items[i++]); } }while(--iterations);