This example displays an example of Duff's Device implemented in JavaScript.
The process of looping are in it self expensive. Doing a for loop is more expensive than a while
loop and so on... Duff's Device is a technique to cut down the number of iterations in a loop which boosts speed on an
operation. On large number of iterations Duff's Device performs from 50 - 70% faster than a traditional loop.
Duff's Device is build on the theory that this:
var j = 0;
j++;
j++;
j++;
j++;
j++;
j++;
j++;
j++; // which is 8
is faster than this:
var j = 0;
var i = 8;
while(--i){
j++;
}
So by doing something like this:
var l = 8; // will be just one.. just a example
var j = 0;
var i = parseInt(l / 8);
do{
j++;
j++;
j++;
j++;
j++;
j++;
j++;
j++;
}while(--i);
we are doing eight times less iterations than with an old fashion loop. In other words; if we have a list of 64 items we want to iterate over we can cut it down to eight iterations with Duff's Device (if we implement Duff's Device to operate with a division of 8). A traditional loop would use 64 iterations.
These tests perform the same operations (adding one to a variable) in both a traditional descending while loop and with Duff's Device. The intention of the tests are just to time the looping. NOTE: The largest number of iterations can halt your browser!
Code for this test here.
This page is a result of techniques described by Tom Duff
Page by: Trygve Lie