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

I am prone to "if-conditional syndrome" which means I tend to use if conditions all the time. I rarely ever use the ternary operator. For instance:

//I like to do this:
int a;
if (i == 0)
{
a = 10;
}
else
{
a = 5;
}


//When I could do this:
int a = (i == 0) ? 10:5;

Does it matter which I use? Which is faster? Are there any notable performance differences? Is it a better practice to use the shortest code whenever possible?

148052 次浏览

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

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

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.

It's best to use whatever one reads better - there's in all practical effect 0 difference between performance.

In this case I think the last statement reads better than the first if statement, but careful not to overuse the ternary operator - sometimes it can really make things a lot less clear.

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

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?

Try to use switch case statement but normally it's not the performance bottleneck.

Also, the ternary operator enables a form of "optional" parameter. Java does not allow optional parameters in method signatures but the ternary operator enables you to easily inline a default choice when null is supplied for a parameter value.

For example:

public void myMethod(int par1, String optionalPar2) {


String par2 = ((optionalPar2 == null) ? getDefaultString() : optionalPar2)
.trim()
.toUpperCase(getDefaultLocale());
}

In the above example, passing null as the String parameter value gets you a default string value instead of a NullPointerException. It's short and sweet and, I would say, very readable. Moreover, as has been pointed out, at the byte code level there's really no difference between the ternary operator and if-then-else. As in the above example, the decision on which to choose is based wholly on readability.

Moreover, this pattern enables you to make the String parameter truly optional (if it is deemed useful to do so) by overloading the method as follows:

public void myMethod(int par1) {
return myMethod(par1, null);
}

For the example given, I prefer the ternary or condition operator (?) for a specific reason: I can clearly see that assigning a is not optional. With a simple example, it's not too hard to scan the if-else block to see that a is assigned in each clause, but imagine several assignments in each clause:

if (i == 0)
{
a = 10;
b = 6;
c = 3;
}
else
{
a = 5;
b = 4;
d = 1;
}


a = (i == 0) ? 10 : 5;
b = (i == 0) ? 6  : 4;
c = (i == 0) ? 3  : 9;
d = (i == 0) ? 12 : 1;

I prefer the latter so that you know you haven't missed an assignment.