"I feel a combination of pride and revulsion at this discovery. If no one's thought of it before, I think I'll name it after myself." - Tom Duff, Nov 1983

the brown-dragon blog

Duff's Device

2009-08-21

I find it sad that many programmers today, even those that use C/C++ extensively are unaware of gems like Duff's Device. To correct this glaring deficiency (and for the fun of it), I'll give a brief explanation here.

Those of you who think you know the ins-and-outs of C/C++ prepare to be outraged and amazed! (Drum roll please...)

Duff's device was invented by Tom Duff when he was at Lucasfilm. He was trying to optimize an inner loop which was the bottleneck in a real-time animation playback. Through some weird and wonderful process of thought (possibly he fell on his head) he came up with the most dramatic use yet of the fall-through in a C switch case.

Basically in his enlightened state, he realized that the unrolled version of the loop could be implemented by INTERLACING the structures of a switch and a loop.

duffdevice.c

  register n = (count + 7) / 8;      /* count > 0 assumed */

  switch (count % 8)
  {
  case 0:        do {  *to = *from++;   /* <<- Note the start of the */
  case 7:              *to = *from++;       /* do {}while loop INSIDE */
  case 6:              *to = *from++;           /* the switch statement */
  case 5:              *to = *from++;
  case 4:              *to = *from++;
  case 3:              *to = *from++;
  case 2:              *to = *from++;           /* This strange (and frankly */
  case 1:              *to = *from++;       /* slightly disgusting) loop */
                     } while (--n > 0); /* <<-ends here! :-) */
  }

Here the switch case allows us to "jump into" the middle of the running loop at a correct position for the unrolling to work correctly.

Strange and disgusting it may be - but this is perfectly VALID C! Stare at it for a while and be amazed! :-D

I'll end with a quote from the great man himself:

"Many people ... have said that the worst feature of C is that switches don't break automatically before each case label. This code forms some sort of argument in that debate, but I'm not sure whether it's for or against.
yrs trly
Tom"

Other Posts

(ordered by Tags then Date)