三元运算符是否比“if”运算符快。 Java中的条件 [英] Is the ternary operator faster than an "if" condition in Java

查看:164
本文介绍了三元运算符是否比“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").

这篇关于三元运算符是否比“if”运算符快。 Java中的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆