Duff's Device
- From: Hallvard B Furuseth <h.b.furuseth@xxxxxxxxxxx>
- Date: Thu, 28 Sep 2006 17:36:07 +0200
I've been wondering sometimes:
Anyone know why Duff's device is usually written like this:
void duff(const char *str, int len) {
int n = (len + 7) / 8;
switch (len % 8) {
case 0: do{ foo(*str++);
case 7: foo(*str++);
case 6: foo(*str++);
...
case 1: foo(*str++);
} while (--n > 0);
}
}
instead of this?
void duff2(const char *str, int len) {
switch (len % 8) {
case 0: while ((len -= 8) >= 0) {
foo(*str++);
case 7: foo(*str++);
case 6: foo(*str++);
...
case 1: foo(*str++);
}
}
}
The original has an extra '+' and doesn't handle len=0.
Nor does it need the divide by 8, though I realize n-=1
may be cheaper than n-=8 on some architectures.
People have had 18 years to notice now:-)
--
Hallvard
.
- Follow-Ups:
- Re: Duff's Device
- From: Rod Pemberton
- Re: Duff's Device
- From: Laurent Deniau
- Re: Duff's Device
- From: Hallvard B Furuseth
- Re: Duff's Device
- Prev by Date: Re: How function works internally
- Next by Date: Re: Duff's Device
- Previous by thread: reading a file
- Next by thread: Re: Duff's Device
- Index(es):
Relevant Pages
|
|