Duff’s Device in JavaScript

We’re going to be discussing efficient JavaScript in some upcoming training sessions, and I wanted to get this code snippet out for discussion.

Commonly, developers will process an array of values, calling some pre-defined function with this idion:

var i=values.length;
while (i--){
    process(values[i]);
}

In most modern browsers, this is fairly efficient that for small enough objects it does present much of a performance bottle-neck. For large arrays on less modern browsers, this can cause performance slow-downs. Nicholas C. Zakas (@slicknet) in his book, Even Faster Web Sites (O’Rielly) presents a faster alternative.

var iterations = Math.floor(values.length / 8);
var leftover = values.length % 8;
var i = 0;

if (leftover > 0){
    do {
        process(values[i++]);
    } while (--leftover > 0);
}

do {
    process(values[i++]);
    process(values[i++]);
    process(values[i++]);
    process(values[i++]);
    process(values[i++]);
    process(values[i++]);
    process(values[i++]);
    process(values[i++]);
} while (--iterations > 0);

From Speed Up Your Site (New Riders).

Leave a Reply

Your email address will not be published. Required fields are marked *