News for hackers. Stuff that matters.
Re:Guide to Implementing Communication Protocols in C++ for ... by vardump on Tuesday June 12, 2018 @08:16AM (#17292526)
Switch is efficient on pretty much any platform I can think of (well, except some 8-bit uC compilers...).

That statement about switch inefficiency is simply not true, except for sparse case values.

But since one can generally choose those values (and they're often a running enum anyways), it's really a non-issue.

For sparse case, it's better to use a hash table. Perhaps a build phase to generate a perfect hash (https://en.wikipedia.org/wiki/Perfect_hash_function) to map each possible input value to continuous range of integer values.

Re:Guide to Implementing Communication Protocols in C++ for ... by brandmeyer on Tuesday June 12, 2018 @09:03AM (#17292794)
> except for sparse case values

Even for sparse case values the compiler will emit a binary search once the list of labels is long enough.

Re:Guide to Implementing Communication Protocols in C++ for ... by convolvatron on Tuesday June 12, 2018 @10:51AM (#17293756)
i’m pretty sure i’ve heard of compilers generating a perfect hash (since the key space is known) also
Re:Guide to Implementing Communication Protocols in C++ for ... by vardump on Tuesday June 12, 2018 @10:59AM (#17293853)
This has been my expectation as well, but haven't seen this in real life.

I guess the main issue is that the compiler will need to also ensure no value outside the expected set can match a case statement either (no match and default cases), which kinda negates the benefit.

Maybe there are cases this is generated, anyone seen compiler generating those?

I wonder whether it is possible to generate reversible (almost) perfect "hashes"?

I mean a hash where every unique input value is guaranteed to map to a unique output value. Because this kind of hash could be used to handle no-match/default case safely.