Hacker News new | past | comments | ask | show | jobs | submit login

I may be dumb, but what is "goto *ptr;" useful for? Or &&foo.





It's used in VMs, emulators, and other interpreters for making a dispatch loop with less branching than a standard loop with a switch inside it.

https://eli.thegreenplace.net/2012/07/12/computed-goto-for-e...


No, it has the same number of branches as a switch inside. The only difference is that computed goto switches miss the initial range check. And proper switch implementations by a better compiler would be more optimizable. But we are waiting more than 20 years for that already. Sparse switch dispatch tables are also compiled horribly.

No, it doesn't, because in a switch with a loop, at the end of each case (after the break), the instructions have an unconditional jump to the top of the switch again, where it performs the indirect jump. With the code using computed goto, the indirect jump is at the end of every single case of the switch. You can see this in the assembly the author provides. I'm ignoring cases where there's fallthrough to another case of the switch, which is sometimes done in interpreters like these. And though I wasn't thinking of it, the lack of a bounds check also reduces the number of branches.

The reduced branching used to bring speed improvements due to better branch prediction, though they have shrunken and become smaller and smaller on newer CPUs as branch prediction has improved in general.

The fact that they had become increasingly miniscule was acknowledged even ten years ago:

Nehalem shows a few outstanding speedups (in the 30%–40% range), as well as Sandy Bridge to a lesser extent, but the average speedups (geomean of individual speedups) for Nehalem, Sandy Bridge, and Haswell are respectively 10.1%, 4.2%, and 2.8% with a few outstanding values for each microarchitecture. The benefits of threaded code decreases with each new generation of microarchitecture.

https://inria.hal.science/hal-01100647/document


error conditions when you don't have exceptions:

    goto *errOrSuccess;
is a pretty normal one. This basically allows you to emulate a "finally".

State machines are another big one, which look much nicer with computed goto than a switch statement.




Join us for AI Startup School this June 16-17 in San Francisco!

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

Search: