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

查看:90
本文介绍了三元运算符是否比“if"运算符更快?Java中的条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我容易出现if 条件综合症",这意味着我总是倾向于使用 if 条件.我很少使用三元运算符.例如:

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.

哪个更快?

都不是.

尽可能使用最短的代码是更好的做法吗?

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天全站免登陆