The fastest work is the work you do not do. Three ways to do less on every message, and one way to make small decisions cheaper:
- Lookup tables. If a function of a small input (a byte, a message type, a price band) is slow or full of
ifs, compute all its answers once into an array and index the array on the hot path.
- Search smarter. On sorted data,
std::lower_bound finds a position in about log2(n) comparisons instead of n.
- Hoist invariant work. A call whose result is the same on every pass of a loop belongs before the loop.
- Fewer branches. Processors guess the direction of each branch and run ahead; a wrong guess throws that work away. For small decisions,
std::min and std::max usually compile to code with no branch at all.
You cannot see branch predictions from a browser, and timings here would be noise, so these exercises count the work instead: how often a slow function runs, how many comparisons a search makes. The tests provide the counted functions.
A table moves the slow work to start-up.