Branchless Programming: Appropriate for everything?

When it comes to programming, it's not about how many lines of code you write or how complex your program appears at first glance; it's all about finding the most effective solution to a problem. Forget about your massive, ultimate programmer ego and look for the most simple solution instead of overthinking or overlooking the most simple pathways.

Let's focus on the keyword "simple" from that paragraph, what comes to your mind when you think about this when it comes to writing an application? Whatever your answer is, it's probably slightly different from mine. Why? Because there are always multiple solutions to a problem and the term "simple" is a very relative term.

Why am I mentioning this when the title of this post is all about branchless programming? Well, before we talk about using branchless programming we need to consider the individual problem and the mindset of the programmer or engineer. It's likely that you have heard about branchless programming before; for a good reason. It's a sometimes controversial topic that seems to vary in opinion from developer to developer.

My advice is simple; if you have an application that has a large time complexity due to poorly optimised code then you should explore every possible option available to you, and branchless programming may or may not be suitable for your specific use case.

Let's suppose that we have a program with 50 if-else statements, do you really think that this is best practice? Or do you think that the code that you have written could be made "modular"? If so, then do it! It's all about being bothered to improve, not just the code you have written but also you as a developer and your technical skillset.

A general guide may look something like what I have written below, however, your own judgment is crucial for your specific use case. Don't blindly follow other developers as it will likely lead you into a rabbit hole that you won't be able to escape from.

You should implement branchless programming if:

1. Your if-else statement/s are repetitive, completing similar but meaningless operations.

2. Your if-else statement/s are too long and call to the same place with different arguments.

3. Your if-else statement/s are overly complex and use a large number of system resources and time to compile.

4. You can understand and reliably replace branches with non-branched methods.

5. The exact metrics of the already existing code are known and require significant improvement.

Comments