r/programming 1d ago

Branch‑Avoidant Programming

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

87 comments sorted by

View all comments

29

u/bodiam 1d ago

That's interesting. Would this also apply to higher languages, like Java, which run on a JVM? (Not intending to rewrite my code, but I'm curious how much languages like Java benefit from branch prediction and brancheless approaches)

19

u/crozone 23h ago

Not sure about Java specifically, but in the .NET framework, a lot of the tight loops within certain algorithms (eg hashing) use code like this, and the JIT has specific optimisations that allow it to emit CMOV when possible and avoid branching.

1

u/randylush 16h ago

A lot of high level languages encourage you to present your code as a problem statement rather than an iterative solution. In this post’s example, a lot of languages allow you to write this as “filter array where values are less than 500” rather than “for each element in the array, if less than 500, add to another array.” IMO it’s always better to code in terms of problem definitions than solutions, because humans will invariably come up with inefficient solutions when they could have just given the compiler the original problem and had it solve it.