Hacker News new | ask | show | jobs
by bena 715 days ago
C and C++ have implicit fall through for switch statements. So without a “break”, each case will execute after the one chosen.

Most control structures compile down to labels and jumps under the hood. That “while” is jumping to that “do” regardless of whether or not we’ve “executed” that line.

Combine those two facts and you have the what. If you go to “case 5”, you’ll execute cases 5, 4, 3, 2, and 1; then jump up to the “do” to continue looping as normal.

As to the why: “loop unrolling”. A technique to eke out performance when things are truly tight.

Executing a loop is work. There are things to add or subtract, comparisons, etc. If you know a loop will execute 4 times, it can be faster to just repeat the statement 4 times.

If your statement is repeated more than that, it can get unwieldy. But you can reduce the number of loops if you know there’s a number you can divide by. If you have to perform 15 loops, you can loop 5 times, repeating your statement 3 times in the loop.

Duff’s device is a way to do this for loops of unknown sizes. The first iteration of the loop essentially begins in the middle of the loop, then each subsequent iteration is done in groups of 8.

It’s old-school “clever” code. And back in the day, it was a way to save clock cycles when that mattered more. I wouldn’t do this today unless everything else has been tried