Looking for smart ways to do a simple value clamp without much if/else branching, I came upon a StackOverflow thread where the same question was asked, but for C.
What surprised me in that thread was mention of ternary operations being more compiler friendly than if/else blocks.
Is this so in Java?
I’m asking mostly because I have a liking for ternary operations, but generally just because the code is compact, although I’ve been discouraged from using them in the past (at work, mostly) due to them being harder to read sometimes.
I always assumed that ternary operators where, under the hood, just a compact form of an if/else block (just like switch operations are, as far as I know).
So this code:
public static double clamp(double value, double min, double max)
{
return value < low? low : value > high? high : value;
}
I though would be equivalent to this:
public static double clamp(double value, double min, double max)
{
if(value < low) return low;
if(value > high)return high;
return value;
}
But now I’m suspecting that assumption is wrong. Am I wrong in my assumption that my assumption is wrong? Or was I right in my previous assumption and thus my current assumption is wrong?
(Yes, on that last line I’m being an asshole)