If the condition is short and the true/false parts are short then a ternary operator is fine, but anything longer tends to be better in an if/else statement (in my opinion).
In terms of speed there should be no difference. Unless you are using a really bad javascript implementation. The slowest part of both statements is the branching.
The only "advantage" is that you can use the ternary operator in an expression (eg. function arguments), making for terser code. using an if , you'd duplicate the full expression.
There should not be a major difference in speed. However, the switch is far more readable and maintainable.
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 ());
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?
Ternary operators are just shorthand. They compile into the equivalent if-else
statement, meaning they will be exactly the same.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With