logoalt Hacker News

Computed goto for efficient dispatch tables (2012)

30 pointsby firephoxlast Wednesday at 1:51 PM11 commentsview on HN

Comments

variadixtoday at 3:54 PM

You can probably eliminate the switch bounds check by making the default case execute __builtin_unreachable(). The switch version is safe for non-conforming opcodes where the computed goto version invokes UB.

jdw64today at 2:40 PM

I understood up to the comparison operations in this article, but I'm having trouble understanding branch prediction even after reading it. It seems like they used branch prediction optimization... Sometimes when I read articles like this, I start to question whether I can really call myself a programmer

show 2 replies
nlytoday at 1:54 PM

All well and good provided your opcodes are sequential/dense

show 1 reply
kibwentoday at 3:25 PM

> Therefore, the standard forces the compiler to generate "safe" code for the switch. Safety, as usual, has cost, so the switch version ends up doing a bit more per loop iteration.

Safety only has a cost in this case because the switch is fundamentally just operating on an integer. With an actual enumerated type (rather than C's primitive "enums as numeric aliases"), which even a basic type system could trivially enforce, there would be no need for this check, because the domain of the value would be guaranteed at compile-time.

show 1 reply
frohtoday at 1:54 PM

(2012)