Branchless Rust: Making a Filter 4x Faster by Removing an If
11 hours ago
- Filtering a slice of numbers by a threshold shows performance varying by selectivity, with 50% being slowest due to branch mispredictions.
- The branch predictor guesses which path to take; unpredictable data causes mispredictions, which are costly (15–20 cycles each).
- Sorted input makes the branch predictable (4.5x faster), but sorting is not a practical fix.
- Branchless programming removes the unpredictable branch by always writing elements and using comparison results as numbers to conditionally advance a cursor.
- Branchless code runs in constant time (~1 ms) regardless of selectivity, but is slower for very predictable cases (e.g., 1% kept).
- This technique should only be used on hot paths with unpredictable branches; readability and best-case performance are traded.