Switching It Up a Bit
xania.org·4d·
Discuss: Hacker News
🧮Algebraic Datatypes
Preview
Report Post

Written by me, proof-read by an LLM. Details at end.

The standard wisdom is that switch statements compile to jump tables. And they do - when the compiler can’t find something cleverer to do instead.

Let’s start with a really simple example:

Here the compiler has spotted the relationship between x and the return value, and rewritten the code as: if (x < 5) return (x+1) * 100; else return 0; - pretty neat. No jump table, just maths!

If we mix up the code a bit so there’s no obvious relationship between the input and the return value:

Still no jump table: Now the compiler has built a bespoke lookup table (CSWTCH.1) and then uses x to index into it (after checking it’s in bounds).

For “dense” case statements, like the ones above, the compiler can be smart. But even w…

Similar Posts

Loading similar posts...