Fixing Duff's Device

While researching for my book, I came across Jeff Greenburg’s JavaScript port of Duff’s Device, a generic way to unroll loops for optimization. Jeff’s original algorithm looks like this:

var iLoopCount = iIterations / 8; 
var iTestValue = iIterations % 8; 
do { 
    switch (iTestValue) { 
        case 0: [execute statement]; 
        case 7: [execute statement]; 
        case 6: [execute statement]; 
        case 5: [execute statement]; 
        case 4: [execute statement]; 
        case 3: [execute statement]; 
        case 2: [execute statement]; 
        case 1: [execute statement]; 
    iTestValue = 0; 
} while (--iLoopCount > 0);

This is, more or less, a direct port from the original C code. The problem is the value of iLoopCount, which will end up as a floating-point value in many situations. Operations involving floating-point numbers are more expensive than those using integers, so this isn’t optimal. To fix this, you can use Math.ceil() to convert the result into an integer:

var iLoopCount = Math.ceil(iIterations / 8);

Remember, the purpose of Duff’s Device is to speed up loop operations, so every little bit helps.

Understanding JavaScript Promises E-book Cover

Demystify JavaScript promises with the e-book that explains not just concepts, but also real-world uses of promises.

Download the Free E-book!

The community edition of Understanding JavaScript Promises is a free download that arrives in minutes.