header

Torsten Curdt’s weblog

Duff device

A while ago I read about the so called “Duff device”. You use it to reduce the counting overhead of loops and to get a better performance when copying memory around. Well, have a look at this valid(!!) C program.


int n = (len + 8 - 1) / 8
switch(len % 8) {
  case 0: do { IOPORT = *pSource++;
  case 7:      IOPORT = *pSource++;
  case 6:      IOPORT = *pSource++;
  case 5:      IOPORT = *pSource++;
  case 4:      IOPORT = *pSource++;
  case 3:      IOPORT = *pSource++;
  case 2:      IOPORT = *pSource++;
  case 1:      IOPORT = *pSource++;
  } while(--n > 0);
}

Isn’t that sick?! …that’s what they call a “duff device”. Looks like someone tricked the parser ;-) It also reminds me on my old AMIGA demo coding times when we generated code without loops to get the optimal performance. On-the-fly binary code generation coded in assembler. I fear that will be considered just as sick these days ;-)

blog comments powered by Disqus