Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

It's really less complex than it appears, especially once you grok that switch/case is just a computed goto; cases are just labels.

So, the idea behind Duff's Device is just to unroll a loop, dealing in an elegant (some would say abhorrent - they're wrong) way with the "leftover" portion.

So, the canonical Duff's is copying shorts, with the copy loop unrolled to eight copy statements inside the loop. If you want to copy, say 47 shorts, the loop would need to iterate five times, and there would be seven shorts left to copy.

Duff's uses the switch to jump into the middle of the loop just far enough to copy those seven leftover shorts (47 % 8 = 7). The do-while then proceeds to run through the five full iterations.

Modern compilers will do that for you now, though there are still applications for similar code.

Hope that helps.



Okay, this definitely helps but I'm still struggling (sorry), I'm probably focusing too much on minutiae but:

* At the static level, what does it mean to start the loop at `case 0` then fall through to the termination of the loop? Part of me is surpisued that it even compiles (again, sorry); it's like the mechancis of the loop itself become dependent on the runtime input, at which point my brain begins to frazzle gently.

* Why is the `to` pointer never incremented? Is that some super-clever thing that I'm not seeing or is it just left out of the algorithm for clarity?

(EDIT: Formatting)


- case 0 is first, because this indicates that the modulo operation in the switch statement (count % 8) has no remainder, i.e., all 8 copy instructions should be executed. So, this is first because of the properties of the modulo operation.

- the to pointer is not incremented because it corresponds to a single memory mapped output register (http://en.wikipedia.org/wiki/Duff%27s_device#Original_versio...). It does not have anything to do with the use if Duff's device.

hth




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: