3

I recently heard about branchless programming and found some simple examples like:

int getSmaller( int a, int b )
{
    if ( a < b )
        return a;
    else
        return b;
}

Which can be written as

int getSmaller( int a, int b )
{
    return a * ( a < b ) + b * ( b <= a );
}

This all works because a < b returns true/false or in cpp 1/0. I am mainly programming in Java in as far as I know true/false is not equal to 1/0 so how would you write a similar solution in Java

René
  • 358
  • 1
  • 10
  • 3
    *"how would you write a similar solution"* - Honestly, I think a better question is **why** would one write a similar solution? This is the first I've heard of "branchless programming" but from this example alone it looks like an endeavor to make code more esoteric/obtuse and difficult to support. – David Jul 28 '20 at 17:11
  • 3
    In Java, you're expected to trust the compiler to do optimizations of this level instead of trying to outsmart it. You should make code changes only when you observe the compiler is not generating the efficient code you expected it to generate. – Joni Jul 28 '20 at 17:33
  • 2
    Two find the smallest of two `int`, also consider to use `Math.min`, which is intrinsified. – Glains Jul 28 '20 at 17:46
  • 1
    @David - well, I never heard the term, but I do prefer "not jumpy around programming". For example, instead of `if (x) foo("this"); else foo("that")` I write `foo(x ? this : that)` which better captures the meaning of what I am doing - calling a function with an argument that depends on `x`. – user13784117 Jul 29 '20 at 01:28
  • But, "multiplying by the result of a comparison" is pretty ancient art, handy in the 1970s if you were stuck with a language that didn't have conditional expressions. I would not recommend it nowadays. – user13784117 Jul 29 '20 at 01:31
  • 2
    @David branchless programming can exponentially increase performance of a program (if done right), it is definitely not just "an endeavor to make code more esoteric/obtuse", however, Joni is right, in Java, the compiler already makes a lot of these kind of optimizations in the background. – KiwiNinja Oct 12 '20 at 20:38

0 Answers0