From TheBestLinks.com
In computer science, Duff's device is an optimised implementation of a serial copy.
It is perhaps the most dramatic use yet seen of fall through in the C programming language, and was invented by Tom Duff when he was at Lucasfilm. Whilst optimising an inner loop that copied data serially onto an output port, he decided to unroll it. He then realised that the unrolled version could be implemented by interlacing the structures of a switch and a loop:
register n = (count + 7) / 8; /* count > 0 assumed */
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);
}
Based on a widely-used assembly language algorithm for minimizing the number of tests and branches during a copy, it appears out of place when implemented in C. The device is indeed perfectly valid, legal C, and many compilers will optimize the switch into a jump table just as would be done in an assembler implementation. C's default fall through in case statements has long been its most controversial single feature; Duff observed that "This code forms some sort of argument in that debate, but I'm not sure whether it's for or against."
External links
Related links
Top visited
0 of
0 links
[no links posted yet]
>> place link >>
Discussion
Last posted
0 of
0 messages
[no messages posted yet]
>> post message >>
Watch
You can
add this article to your own "watchlist" and receive e-mail notification about all changes in this page.