r/programming 1d ago

Branch‑Avoidant Programming

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

87 comments sorted by

View all comments

139

u/meamZ 23h ago

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...

39

u/SwingOutStateMachine 21h ago

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.

8

u/SanityInAnarchy 16h ago

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

4

u/Ameisen 16h ago

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).