Jeff Greenberg的Duff装置技术代码:通过将values数组中元素个数除以8来计算出循环需要进行多次迭代的。 //credit: Jeff Greenberg for JS implementation of Duff‘s Device //假设values.length > 0 var iterations = Math.ceil(values.length / 8); var startAt = values.length % 8; var i = 0;
do{ switch(startAt){ case 0: process(values[i++]); case 1: process(values[i++]); case 2: process(values[i++]); case 3: process(values[i++]); case 4: process(values[i++]); case 5: process(values[i++]);
case 6: process(values[i++]); case 7: process(values[i++]); }
startAt = 0; } while (--iterations > 0);
由Andrew B.King 所著的Speed Up your Site(New Riders,2003),提出了一个更快的Duff装置技术,将do-while循环分成2个单独的循环。一下是例子: //credit: Speed Up your Site(New Riders,2003) var iterations = Math.floor(values.length / 8); var leftover = values.length % 8;