三元运算符是否比“if”运算符快。 Java中的条件
我倾向于 if-conditional syndrome ,这意味着我倾向于一直使用条件。我很少使用三元运算符。例如:
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?
这对我来说是否重要使用?
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?
两者都没有。
使用最短的是更好的做法尽可能的代码?
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").