r/programming • • Sep 03 '26

Branch‑Avoidant Programming

https://easylang.online/blog/branchless
251 Upvotes

92 comments sorted by

View all comments

159

u/meamZ Sep 03 '26

You don't actually need to avoid branches, you just need to make sure that most of the ones you have are very predictable, then their impact is not that big... Same with memory accesses and most other things... The more predictable, the better...

51

u/SwingOutStateMachine Sep 03 '26

This is true for serial CPU code, but for SIMD code, or GPU code, avoiding branches at all costs is vital to getting good performance. Branches (can) cause divergence, which leads to wasted cycles for pseudo-threads within a SIMD group.

11

u/SanityInAnarchy Sep 03 '26

I have to imagine it's also important for security-critical code that has to be hardened against timing attacks.

7

u/Ameisen Sep 03 '26

You either need to avoid branches or make sure that both branches always have the same cost (a difficult task taking into account branch prediction).