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.

Disclaimer: Any viewpoints and opinions expressed in this article are those of Nicholas C. Zakas and do not, in any way, reflect those of my employer, my colleagues, Wrox Publishing, O'Reilly Publishing, or anyone else. I speak only for myself, not for them.