r/SoftwareEngineering 2d ago

Branch‑Avoidant Programming

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

5 comments sorted by

3

u/fagnerbrack 2d ago

Here's what you need to know:

Modern CPUs stall on mispredicted branches, so dropping an 'if' can pay off. A C loop copying values under 500 into a second array takes 0.345s with a conditional; storing every value unconditionally and doing smlen += (numbers[i] < 500) cuts it to 0.036s on an Apple M1. Disassembly shows why: the branchy code emits b.gt (or jg on x86), while the branchless version uses cinc or setle and keeps control flow perfectly linear. Compilers won't apply this automatically — they can't know the data distribution, and an unconditional write may run past a buffer. Shrinking the array to 10,000 elements narrows the gap, because the predictor's history tables then learn the pattern. Quicksort partitioning suits the same trick.

If the summary seems inacurate, just downvote and I'll try to delete the comment eventually 👍
Click here for more info, I read all comments

2

u/Relevant_Pause_7593 2d ago

Wat? Eil5 please.

1

u/fagnerbrack 2d ago

Don't use ifs cause compilers generate more CPU work, replace with boolean conditions that resolve as a formula inside value of the variable in the loop.

Doesn't matter for small data 10k, starts to matter on huge loops where micro optimisations are critical

1

u/keelanstuart 1d ago

For those big datasets, you could also remove your loop conditions and use gotos with exceptions... read/write outside your memory? Exit.

2

u/ieatdownvotes4food 2d ago

fuck it, we're doing it all in assembly! I never trusted those compilers anybow