Duff's Device - Original Version

Original Version

Straightforward code to copy items from an array to a memory-mapped output register might look like this:

do { /* count > 0 assumed */ *to = *from++; /* Note that the 'to' pointer is NOT incremented */ } while(--count > 0);

Note that this is not a memory-to-memory copy, in which you would see *to++.

While optimizing this, Duff realized that an unrolled version of his loop could be implemented by interlacing the structures of a switch and a loop.

send(to, from, count) register short *to, *from; register count; { register n = (count + 7) / 8; switch(count % 8) { case 0: do { *to = *from++; case 7: *to = *from++; case 6: *to = *from++; case 5: *to = *from++; case 4: *to = *from++; case 3: *to = *from++; case 2: *to = *from++; case 1: *to = *from++; } while(--n > 0); } }

Notice that Duff's device can just as easily be applied with any other size for the unrolled loop, not just 8.

Read more about this topic:  Duff's Device

Famous quotes containing the words original and/or version:

    “We Americans are supposed to be overly concerned about the child. But actually the intelligent care of children in our society is balanced by a crass indifference to the helplessness of infancy and youth. Cruelty to children has become more widespread but less noticed in the general unrest, the constant migration, the family disintegration, and the other manifestations of a civilization that has been torn away from its original moorings.”
    —Agnes E. Meyer (1887–1970)

    “Remember that you were a slave in the land of Egypt, and the LORD your God brought you out from there with a mighty hand and an outstretched arm; therefore the LORD your God commanded you to keep the sabbath day.”
    —Bible: Hebrew, Deuteronomy 5:15.

    See Exodus 22:8 for a different version of this fourth commandment.