Branchless Rust: How Removing an if Made a Filter 4x Faster

Branchless Rust: Making a Filter 4x Faster by Removing an If

Branchless Rust: How Removing an if Made a Filter 4x Faster

Filtering a slice of numbers sounds trivial, but a simple `if` can tank performance when the data is unpredictable. Serhii Potapov discovered that his idiomatic Rust filter was 4x slower on shuffled data than on sorted data, due to branch mispredictions. By rewriting the filter to use arithmetic instead of a branch—always writing and conditionally advancing—he made the worst case 4x faster and independent of data order. The trade-off: the best case gets slower, so branchless programming is only worth it for hot paths.

A branch is cheap. A mispredicted branch is not.

More from this day

2026-08-06