Branchless Rust: Making a Filter 4x Faster by Removing an If
- Programming
- Hardware
- Developer Tools
- AI
The post benchmarks a simple Rust filter over `f64` values and shows that the slow case was not allocation but an unpredictable branch. Rewriting the loop so it always writes to `out[n]` and only conditionally increments `n` flattened the runtime across inputs and made the 50 percent keep-rate case much faster. The catch is that this version preallocates output space for the entire input and performs many writes that later get overwritten, so it buys steadier latency by spending more memory bandwidth and more output capacity than the final result may need.
If you own a hot loop, benchmark branch predictability and memory traffic separately before you celebrate a branchless rewrite. For bigger wins, look past scalar tricks to SIMD stream compaction, and do not assume the compiler will discover that path for you.
-
greyblake.com
- Discuss on HN