三元运算符是否比 Java 中的“if”条件更快
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9745389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is the ternary operator faster than an "if" condition in Java
提问by JRunner
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 综合征”,这意味着我总是倾向于使用 if 条件。我很少使用三元运算符。例如:
//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?
我使用哪个重要吗?哪个更快?是否有任何显着的性能差异?尽可能使用最短的代码是更好的做法吗?
回答by Konrad Rudolph
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”).
不是“只要有可能”,而是肯定会在没有不利影响的情况下尽可能。较短的代码至少可能更具可读性,因为它专注于相关部分而不是偶然的影响(“样板代码”)。
回答by Jon Egeland
Ternary operators are just shorthand. They compile into the equivalent if-else
statement, meaning they will be exactlythe same.
三元运算符只是速记。它们编译成等效的if-else
语句,这意味着它们将完全相同。
回答by Jon Skeet
If there's anyperformance 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 reallyuseful in some cases. In the specific example you gave, I'd definitely use the conditional operator.
话虽如此,试着克服你对条件运算符的厌恶——虽然它肯定有可能过度使用,但它在某些情况下确实很有用。在您给出的具体示例中,我肯定会使用条件运算符。
回答by Michael Berry
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 语句读起来更好,但要注意不要过度使用三元运算符 - 有时它确实会使事情变得不那么清楚。
回答by user unknown
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 ());
回答by foupfeiffer
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 stackoverflow answer at To ternary or not to ternary?
ps 非常完整的 stackoverflow 答案在To ternary or not to ternary?
回答by Zava
Try to use switch case
statement but normally it's not the performance bottleneck.
尝试使用switch case
语句,但通常它不是性能瓶颈。
回答by scottb
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);
}
回答by Matthew Carlson
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.
我更喜欢后者,这样你就知道你没有错过任何任务。