r/programming • • Aug 22 '26

The unlikely Linux macro

https://rushed-reflections.bearblog.dev/an-unlikely-experiment/

Wrote a bit about the `unlikely` and `likely` macros in the Linux codebase. Great little exploration into tiny optimizations that everyone should know more about 😄

188 Upvotes

61 comments sorted by

View all comments

Show parent comment

20

u/bpikmin Aug 23 '26

Overall, yes, but one small nuance. Instruction order does matter to the branch predictor when the branch is cold (branch predictor cache has no entry for it). Generally your hot path should be small enough that all branches can fit in the branch predictor cache but that might not always be achievable or controllable

7

u/standard_revolution Aug 23 '26

And some branch predictor by default assume that branches are taken/not-taken, so it might make sense to reorder instructions to make the likely branch the one that does/does not jump