[prev] [index] [next]

Efficiency Tricks (cont)

Duff's device (a hideous but clever "optimisation"):

i = 0;  n = lengthOfArray;
switch (n%4) {
case 0: while (i < n) {
        a[i] = b[i] + c[i]; i++;
case 3: a[i] = b[i] + c[i]; i++;
case 2: a[i] = b[i] + c[i]; i++;
case 1: a[i] = b[i] + c[i]; i++;
} }

Implements a partially-unrolled loop.

Interlaces switch and while; exploits case fall-through.
But may clash with look-ahead/pipelining of modern architectures.