Live data from Hacker News

Function Dispatch Tables in C (2019)

blog.alicegoldfuss.com

1–10 of 52 posts

Re: Function Dispatch Tables in C (2019)

#6
For readability, this is reasonable. There may be a cost that it weakens some static analyzers, but I don't program in C enough to be sure.

For performance, this is not necessary because the compiler can optimize long switch-case flow into dispatch tables: https://godbolt.org/z/7WxEfc6YM

Re: Function Dispatch Tables in C (2019)

#7
post #2

I was expecting some form of benchmark to see if claims about better performance is true.

Expecting jump tables to have higher performance than the alternatives sounds definitely iffy, this also reads as if the author doesn't know that switch-case statements also just use a jump table under the hood if the case-blocks are continuous.

Regarding performance, if the CPU branch predictor works well the jump indirection overhead might disappear completely, but that's still not as good as if the compiler can inline the destination function, and jump tables usually prevent that.

(a switch-case dispatcher might actually be better than a traditional function pointer jump table, because the switch-case eliminates some function entry/exit "ceremony", also see "computed goto")

Re: Function Dispatch Tables in C (2019)

#8
post #2

I was expecting some form of benchmark to see if claims about better performance is true.

I'm also dubious on the claim the switch statement is O(n). It might be in a pathological worst case, but you can pretty much bet the compiler is going to transform it into a jump table or other optimized execution (maybe a computed jump). Especially when the cases are contiguous like this...

I agree that a benchmark is warranted, or at least a comparison of the generated assembly (at different optimization levels).

Re: Function Dispatch Tables in C (2019)

#9
I prefer the flexibility of computed gotos a GCC extension that is likely the fastest dispatch method outside of compile-time. With computed gotos, you can have arbitrary dispatch complexity and structure, interleave code(e.g./code1/ ;skip_label: ;label1: /code2/; goto *return_loc;) and use assembler-like tricks to reduce fast paths(e.g. switch off code segment execution or alter control flow on the fly)

Re: Function Dispatch Tables in C (2019)

#10
post #2

I was expecting some form of benchmark to see if claims about better performance is true.

I'm also dubious on the claim the switch statement is O(n). It might be in a pathological worst case, but you can pretty much bet the compiler is going to transform it into a jump table or other optimized execution (maybe a computed jump). Especially when the cases are contiguous like this... I agree that a benchmark is warranted, or at least a comparison of the generated assembly (at different optimization levels).

Also, O(n) doesn’t mean much when the CPU can execute hundreds of checks in a few tens of cycles.
Post reply on HN