🔗 Duffs Device
In the C programming language, Duff's device is a way of manually implementing loop unrolling by interleaving two syntactic constructs of C: the do-while loop and a switch statement. Its discovery is credited to Tom Duff in November 1983, when Duff was working for Lucasfilm and used it to speed up a real-time animation program.
Loop unrolling attempts to reduce the overhead of conditional branching needed to check whether a loop is done, by executing a batch of loop bodies per iteration. To handle cases where the number of iterations is not divisible by the unrolled-loop increments, a common technique among assembly language programmers is to jump directly into the middle of the unrolled loop body to handle the remainder. Duff implemented this technique in C by using C's case label fall-through feature to jump into the unrolled body.
Discussed on
- "Duff's Device" | 2020-05-25 | 145 Upvotes 59 Comments
- "Duffs Device" | 2016-10-21 | 19 Upvotes 4 Comments
- "Duff's device: do + switch fall-through = loop unrolling" | 2009-08-13 | 16 Upvotes 11 Comments