This question already has an answer here:
这个问题在这里已有答案:
- Which “if” construct is faster - statement or ternary operator? 5 answers
哪个“if”构造更快 - 语句或三元运算符? 5个答案
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:
我倾向于“if-conditional syndrome”,这意味着我倾向于一直使用条件。我很少使用三元运算符。例如:
//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?
我使用哪个问题?哪个更快?是否存在显着的性能差异?尽可能使用最短的代码是一种更好的做法吗?
9 个解决方案
#1
96
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”).
不是“只要有可能”,但在任何可能的情况下都不会产生不利影响。较短的代码至少可能更具可读性,因为它侧重于相关部分而不是偶然影响(“样板代码”)。
#2
32
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.
话虽如此,试着克服你对条件运算符的厌恶 - 虽然它有可能过度使用它,但它在某些情况下确实很有用。在你给出的具体例子中,我肯定会使用条件运算符。
#3
26
Ternary Operator example:
三元运算符示例:
int a = (i == 0) ? 10 : 5;
You can't do assignment with if/else like this:
你不能用if / else这样做:
// 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 / else不是那么多代码:
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.
在性能危急情况下:测量它。如果存在瓶颈,请使用目标计算机(目标JVM)测量它,并使用典型数据。否则为了可读性。
Embedded in context, the short form is sometimes very handy:
嵌入在上下文中,简短形式有时非常方便:
System.out.println ("Good morning " + (p.female ? "Miss " : "Mister ") + p.getName ());
#4
15
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).
与简单的语法结构相比,更快(高性能)编码与循环和对象实例化更相关。编译器应该处理优化(它将完全相同的二进制文件!)所以你的目标应该是你从未来的效率(人类永远是软件的瓶颈)。
Josh Bloch's "Performance Anxiety" talk on Parleys.com
Josh Bloch在Parleys.com上的“表现焦虑”谈话
The answer citing 9 lines versus one can be misleading: less 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).
引用9行与1行的答案可能会产生误导:较少的代码行并不总是更好。在有限的情况下,三元运算符可以更简洁(您的示例很好)。
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:
还要考虑将来的可维护性,if-else更容易扩展或修改:
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 * answer at To ternary or not to ternary?
附:非常完整的*回答To三元或不三元?
#5
8
Ternary operators are just shorthand. They compile into the equivalent if-else
statement, meaning they will be exactly the same.
三元运算符只是简写。它们编译成等效的if-else语句,这意味着它们将完全相同。
#6
4
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.
此外,三元运算符启用“可选”参数的形式。 Java不允许方法签名中的可选参数,但是三元运算符使您可以在为参数值提供null时轻松内联默认选项。
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.
在上面的示例中,将null作为String参数值传递给您一个默认字符串值而不是NullPointerException。它简短而且甜美,我想说,非常可读。而且,正如已经指出的那样,在字节码级别,三元运算符和if-then-else之间确实没有区别。如上例所示,选择哪个决定完全取决于可读性。
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:
此外,通过重载方法,此模式使您可以使String参数真正可选(如果认为这样做有用):
public void myMethod(int par1) {
return myMethod(par1, null);
}
#7
2
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:
对于给出的示例,我更喜欢三元或条件运算符(?),原因是:我可以清楚地看到分配a不是可选的。举一个简单的例子,扫描if-else块并不难看出每个子句中都分配了a,但想象一下每个子句中的几个赋值:
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.
我更喜欢后者,所以你知道你没有错过任务。
#8
0
It's best to use whatever one reads better - there's in all practical effect 0 difference between performance.
最好使用任何一个更好的读取 - 在所有实际效果0性能之间的差异。
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.
在这种情况下,我认为最后一个语句比第一个if语句读得更好,但要注意不要过度使用三元运算符 - 有时它确实会使事情变得不那么清楚。
#9
0
Try to use switch case
statement but normally it's not the performance bottleneck.
尝试使用switch case语句,但通常不是性能瓶颈。
#1
96
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”).
不是“只要有可能”,但在任何可能的情况下都不会产生不利影响。较短的代码至少可能更具可读性,因为它侧重于相关部分而不是偶然影响(“样板代码”)。
#2
32
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.
话虽如此,试着克服你对条件运算符的厌恶 - 虽然它有可能过度使用它,但它在某些情况下确实很有用。在你给出的具体例子中,我肯定会使用条件运算符。
#3
26
Ternary Operator example:
三元运算符示例:
int a = (i == 0) ? 10 : 5;
You can't do assignment with if/else like this:
你不能用if / else这样做:
// 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 / else不是那么多代码:
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.
在性能危急情况下:测量它。如果存在瓶颈,请使用目标计算机(目标JVM)测量它,并使用典型数据。否则为了可读性。
Embedded in context, the short form is sometimes very handy:
嵌入在上下文中,简短形式有时非常方便:
System.out.println ("Good morning " + (p.female ? "Miss " : "Mister ") + p.getName ());
#4
15
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).
与简单的语法结构相比,更快(高性能)编码与循环和对象实例化更相关。编译器应该处理优化(它将完全相同的二进制文件!)所以你的目标应该是你从未来的效率(人类永远是软件的瓶颈)。
Josh Bloch's "Performance Anxiety" talk on Parleys.com
Josh Bloch在Parleys.com上的“表现焦虑”谈话
The answer citing 9 lines versus one can be misleading: less 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).
引用9行与1行的答案可能会产生误导:较少的代码行并不总是更好。在有限的情况下,三元运算符可以更简洁(您的示例很好)。
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:
还要考虑将来的可维护性,if-else更容易扩展或修改:
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 * answer at To ternary or not to ternary?
附:非常完整的*回答To三元或不三元?
#5
8
Ternary operators are just shorthand. They compile into the equivalent if-else
statement, meaning they will be exactly the same.
三元运算符只是简写。它们编译成等效的if-else语句,这意味着它们将完全相同。
#6
4
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.
此外,三元运算符启用“可选”参数的形式。 Java不允许方法签名中的可选参数,但是三元运算符使您可以在为参数值提供null时轻松内联默认选项。
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.
在上面的示例中,将null作为String参数值传递给您一个默认字符串值而不是NullPointerException。它简短而且甜美,我想说,非常可读。而且,正如已经指出的那样,在字节码级别,三元运算符和if-then-else之间确实没有区别。如上例所示,选择哪个决定完全取决于可读性。
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:
此外,通过重载方法,此模式使您可以使String参数真正可选(如果认为这样做有用):
public void myMethod(int par1) {
return myMethod(par1, null);
}
#7
2
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:
对于给出的示例,我更喜欢三元或条件运算符(?),原因是:我可以清楚地看到分配a不是可选的。举一个简单的例子,扫描if-else块并不难看出每个子句中都分配了a,但想象一下每个子句中的几个赋值:
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.
我更喜欢后者,所以你知道你没有错过任务。
#8
0
It's best to use whatever one reads better - there's in all practical effect 0 difference between performance.
最好使用任何一个更好的读取 - 在所有实际效果0性能之间的差异。
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.
在这种情况下,我认为最后一个语句比第一个if语句读得更好,但要注意不要过度使用三元运算符 - 有时它确实会使事情变得不那么清楚。
#9
0
Try to use switch case
statement but normally it's not the performance bottleneck.
尝试使用switch case语句,但通常不是性能瓶颈。