Is the ternary operator faster than an "if" condition in Java [duplicate]

Solution 1:

Does it matter which I use?

Yes! The second is vastly more readable. You are trading one line which concisely expresses what you want against nine lines of effectively clutter.

Which is faster?

Neither.

Is it a better practice to use the shortest code whenever possible?

Not “whenever possible” but certainly whenever possible without detriment effects. Shorter code is at least potentially more readable since it focuses on the relevant part rather than on incidental effects (“boilerplate code”).

Solution 2:

If there's any performance difference (which I doubt), it will be negligible. Concentrate on writing the simplest, most readable code you can.

Having said that, try to get over your aversion of the conditional operator - while it's certainly possible to overuse it, it can be really useful in some cases. In the specific example you gave, I'd definitely use the conditional operator.

Solution 3:

Ternary Operator example:

int a = (i == 0) ? 10 : 5;

You can't do assignment with if/else like this:

// invalid:
int a = if (i == 0) 10; else 5;

This is a good reason to use the ternary operator. If you don't have an assignment:

(i == 0) ? foo () : bar ();

an if/else isn't that much more code:

if (i == 0) foo (); else bar ();

In performance critical cases: measure it. Measure it with the target machine, the target JVM, with typical data, if there is a bottleneck. Else go for readability.

Embedded in context, the short form is sometimes very handy:

System.out.println ("Good morning " + (p.female ? "Miss " : "Mister ") + p.getName ()); 

Solution 4:

Yes, it matters, but not because of code execution performance.

Faster (performant) coding is more relevant for looping and object instantiation than simple syntax constructs. The compiler should handle optimization (it's all gonna be about the same binary!) so your goal should be efficiency for You-From-The-Future (humans are always the bottleneck in software).

The answer citing 9 lines versus one can be misleading: fewer lines of code does not always equal better. Ternary operators can be a more concise way in limited situations (your example is a good one).

BUT they can often be abused to make code unreadable (which is a cardinal sin) = do not nest ternary operators!

Also consider future maintainability, if-else is much easier to extend or modify:

int a;
if ( i != 0 && k == 7 ){
    a = 10;
    logger.debug( "debug message here" );
}else
    a = 3;
    logger.debug( "other debug message here" );
}


int a = (i != 0 && k== 7 ) ? 10 : 3;  // density without logging nor ability to use breakpoints

p.s. very complete StackOverflow answer at To ternary or not to ternary?

Solution 5:

Ternary operators are just shorthand. They compile into the equivalent if-else statement, meaning they will be exactly the same.