I understood why Duff's device is faster than normal loop code which can be unrolled but is not optimized. But I can't understand how the code can be compiled yet.
I guess it's a trick about the switch syntax. But not anymore.
How can do while sentence exist in switch sentence? Very weird.
Is there anyone who can explain this?
Edit: Another question. Why did duff use 8? It could be 16, 65536 or whatever. Because of code size? Is there another reason? For example, cache or pipelining benefits.
A simple explanation of why Duff's Device compiles is that the syntax of the
switch
statement isn't particularly specific about the form that theswitch
statement block might need to take. There are a few restrictions, and a couple of things permitted in the controlled statement that aren't permitted outside aswitch
(thecase
anddefault
labels). But other than that, the controlled statement is just any other statement, with the likelihood that there are labels for theswitch
to target.Here's the syntax from C99:
Beyond the syntax, the standard imposes a few constraints:
case
label expressions must be integer constant expressionscase
label expressions ordefault
labelsOther than that, any construct permitted in a statement block should be permitted in the controlled statement (with the addition that
case
anddefault
labels are OK). Remember thatcase
anddefault
are just labels that the switch jumps to based on the controlling expression and thecase
label expressions. As Potatoswatter says,switch
is just a computedgoto
. So just likegoto
can jump into the middle of a loop, so canswitch
.Also, I think that the cases where you might see a benefit from Duff's Device are pretty rare today (I think they were rare even in the 1980's). Don't forget that Tom Duff himself said the following in his description:
Even more than when it was initially described, Duff's Device should be considered more of a curiosity than a tool to use.