129

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?

Erik
  • 503
  • 1
  • 7
  • 26
JRunner
  • 1,437
  • 2
  • 10
  • 10
  • 4
    It doesn't matter and you should rather be concerned about clean code than about performance. In this case, I think the ternary operator is just cleaner. – Niklas B. Mar 16 '12 at 22:40
  • 5
    Also, you can do it like this `if(i == 0) a = 10; else a = 5;` – Eng.Fouad Mar 16 '12 at 22:42
  • 19
    Premature optimization without profiling showing a definite need is bad, bad, bad. Use the code that your future self will best understand 6 months from now. – Hovercraft Full Of Eels Mar 16 '12 at 22:43
  • 2
    I agree with @Niklas, but if you _really_ don't like ternary operator and you don't care about truly trivial performance differences, you could initialize the variable to the default value (presumably 5), and only use an "if" without an "else" to reassign it. – Kevin Welker Mar 16 '12 at 22:44
  • 5
    @Hovercraft: Youself and your coworkers, one is tempted to add here. – Niklas B. Mar 16 '12 at 22:45
  • There are a few rare cases where the ternary operator compiles to a code sequence without branches. But for the most part there's no performance difference (or if there is, it's negligible). Use what's easiest to understand and what makes the logic of your program clearer. – Hot Licks Mar 16 '12 at 23:09
  • 1
    IMHO the Ternary Operator is horrible! – GradAsso Feb 17 '17 at 08:03

9 Answers9

112

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

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 2
    readable doesn't mean it matters, perse. – Jon Egeland Mar 16 '12 at 22:42
  • Even 9 lines, if I count right, because there's also vastly too much whitespace. – Niklas B. Mar 16 '12 at 22:43
  • 29
    @Jon: Yes, it does. Readability is all that matters, effectively. – Niklas B. Mar 16 '12 at 22:43
  • 8
    @Jon If the only difference is readability then readability is *all* that patters. – Konrad Rudolph Mar 16 '12 at 22:44
  • Alright, so the ternary would be more sensible to use, in the example I provided. – JRunner Mar 16 '12 at 22:53
  • 1
    It has a difference in memory consumption & execution time if you can avoid temporary variables using the short way. – xdevs23 Dec 18 '16 at 14:02
  • @xdevs23 Can you explain what your mean by that, preferably with an example? Because the way I understand you this is definitely false. – Konrad Rudolph Dec 18 '16 at 14:05
  • `int blabla = someStaticNumber; if(blabla < 3) blabla += 3; return blabla;`. Instead you could do: `return someStaticNumber < 3 ? someStaticNumber + 3 : someStaticNumber;` – xdevs23 Dec 18 '16 at 15:48
  • @xdevs23 (1) These are not equivalent; you don’t need the temporary variable with the `if` statement, and if you remove it, the two alternatives are identical. (2) I don’t know about Java specifically but generally, any decent compiler will generate identical machine code for your two non-identical statements. — So, no, there’s no difference between using an `if` statement and a conditional operator. – Konrad Rudolph Dec 19 '16 at 10:04
  • Well, I am not sure if the compiler really gets rid of the temporary variable... This was a rather bad example. lol – xdevs23 Dec 19 '16 at 18:34
  • 5
    I'd like to add that ternary is not at all always more readable. Consider `maxSpeed = isParkingLot() ? 5 : ( isInnerCity() ? 50 : 100);` vs. a chain of `if`s or a `switch` statement. Also when the expressions get long (`maxSpeed = map.getStreetType(car.getLocation()) == MapType.PARKING_LOT ? TrafficRules.getMaxSpeed(MapType.PARKING_LOT) : TrafficRules.getMaxSpeed()`), it can be hard to read. – Giszmo Feb 02 '18 at 15:22
  • @Giszmo But `if`s are *not* easier to read in either case. Long conditionals can be split up with temporary variables. [Chained conditional statements can be made readable by breaking them across lines](https://gist.github.com/klmr/a66ac79a4820e3ebc9a73bd26a070b42). That’s an insanely well-established pattern, and is the idiomatic way of dispatching based on conditions in several programming languages. – Konrad Rudolph Feb 02 '18 at 15:49
  • Readability is subjective. There can be a general consensus but no individual agreement. So debating it here is moot. – n00dles Apr 20 '19 at 21:12
34

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    Why would you use the conditional here? I would use the ternary for cleanliness. – Jon Egeland Mar 16 '12 at 22:59
  • 17
    @Jon: The conditional operator is the actual *name* for what you've called the ternary operator. It's *a* ternary operator, as it has 3 operands, but its *name* is the conditional operator. – Jon Skeet Mar 16 '12 at 23:02
  • 2
    Okay, thanks for the clarification. I was thinking you meant the explicit `if-else` syntax. – Jon Egeland Mar 16 '12 at 23:08
29

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 ()); 
user unknown
  • 35,537
  • 11
  • 75
  • 121
  • There's another reason for using the ternary operator - it makes you handle all cases. – Mike Dunlavey Jan 27 '16 at 17:54
  • @MikeDunlavey: If you think of 'Oh, let's not forget the second case! Let's use a ternary operator' you can as well start writing 'else' to not forget it, if your brain is that much unreliable, to forget it in the few seconds of writing your statement. – user unknown Jan 28 '16 at 01:31
  • It's not just a matter of writing the "else", it's what you put in it. – Mike Dunlavey Jan 28 '16 at 13:11
  • @MikeDunlavey: I thought your claim was, that using ? : should help avoid forgetting the else part, which raises the question, how the ? : should prevent forgetting it. Maybe because in most cases, the resulting code will not be correct without it, raising a compiler error? Well, the same can be archived with writing the else-keyword first. Where is the difference? – user unknown Jan 28 '16 at 23:15
14

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?

dev7060
  • 120
  • 8
foupfeiffer
  • 687
  • 7
  • 4
  • 2
    I disagree with this: it’s idiomatic and readable to nest conditional statements, for instance, especially when testing multiple cases as in `return x == 1 ? "one" : x == 2 ? "two" : "many";`. Proper indentation and breaking into multiple lines helps here. – Konrad Rudolph Mar 15 '13 at 00:49
8

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

Jon Egeland
  • 12,470
  • 8
  • 47
  • 62
5

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);
}
aboger
  • 2,214
  • 6
  • 33
  • 47
scottb
  • 9,908
  • 3
  • 40
  • 56
0

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

Erik
  • 503
  • 1
  • 7
  • 26
Zava
  • 743
  • 6
  • 17
  • 3
    It is generally true that solutions employing `switch` blocks should be avoided when they can be. By their nature, `switch` applies to a fixed number of allowable states. This creates a software maintenance liability because "allowable states" is very commonly a moving target. For example, solutions using `enum` classes often work better and more elegantly than solutions based on `switch` blocks. – scottb Oct 02 '15 at 21:02
0

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.

0

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.

Michael Berry
  • 70,193
  • 21
  • 157
  • 216