Hacker News new | ask | show | jobs
by KMag 2264 days ago
You're correct. Many compilers will emit jump tables if the domain is dense enough. Also, even if compiling to a bunch of conditional jumps, they'll usually emit them to require O(log N) conditional jumps (equivalent to a binary tree of nested ifs) instead of the O(N) linear arrangement suggested by the GP.
1 comments

Clang compiles both switch statements and `if` statements to the same tree search code. E.g. https://godbolt.org/z/7M_3PU My point is that the optimizations you're describing for switch statements are also applied to a bunch of `if` blocks, at least in LLVM-based languages with an LLVM version from the last several years.
Sure, I didn't mean to imply that compilers never (or commonly didn't) detect that long if-chains could be optimized to jump tables, lookup tables, or if-trees. I was just answering the more narrow question the GGP was asking: if switch statements were always lowered to if-chains and never compiled to jump tables.
Ah I see, gotcha.