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

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


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”).


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.


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 ());