使用Java的三元运算符,将变量赋给自身的含义是什么?

时间:2021-08-11 22:29:34

I make excessive use of the ternary operator, sometimes even replacing very simple if statements with it. For example, I just found myself replacing something like this:

我过度使用三元运算符,有时甚至用它替换非常简单的if语句。例如,我发现自己更换了这样的东西:

if (foo != null) {
    bar = foo;
}

with this:

bar = (foo == null) ? bar : foo;

While it is a question of taste which one reads nicer, I am wondering:

虽然这是一个人们阅读更好的味道问题,但我想知道:

  • In this case, is the ternary version's performance worse?
  • 在这种情况下,三元版本的性能是否更差?

  • Are there any other reasons against the use of ternary here?
  • 这里是否有任何其他原因反对使用三元?

The reason why I belive the performance could be worse here is that I assume the compiler can't optimize the ternary for when foo is null. Hence, the value of bar might be set to the same value again, wasting some CPU time, where the simple if statement would never get to that point. But my knowledge of compilers and execution is limited, hence the question.

我认为性能可能更差的原因在于我假设编译器在foo为null时无法优化三元组。因此,bar的值可能会再次设置为相同的值,浪费一些CPU时间,其中简单的if语句永远不会到达那一点。但是我对编译器和执行的知识是有限的,因此这个问题。

1 个解决方案

#1


3  

If you've worried about style, you should at least remove the bracket noise:

如果你担心风格,你应该至少删除支架噪音:

bar = foo == null ? bar : foo;

As for performance, you have an unnecessary assignment in the case that foo is null. Big deal. You're talking about nanoseconds.

至于性能,在foo为null的情况下,您有一个不必要的赋值。很重要。你在谈论纳秒。

Don't worry about this insignificant difference of "performance". Worry about readability, which is more important.

不要担心“表现”这种微不足道的差异。担心可读性,这更重要。

In this case, I find the if version more readable:

在这种情况下,我发现if版本更具可读性:

if (foo != null) {
    bar = foo;
}

It's very clear what the intention of the code is.

很清楚代码的用意是什么。

#1


3  

If you've worried about style, you should at least remove the bracket noise:

如果你担心风格,你应该至少删除支架噪音:

bar = foo == null ? bar : foo;

As for performance, you have an unnecessary assignment in the case that foo is null. Big deal. You're talking about nanoseconds.

至于性能,在foo为null的情况下,您有一个不必要的赋值。很重要。你在谈论纳秒。

Don't worry about this insignificant difference of "performance". Worry about readability, which is more important.

不要担心“表现”这种微不足道的差异。担心可读性,这更重要。

In this case, I find the if version more readable:

在这种情况下,我发现if版本更具可读性:

if (foo != null) {
    bar = foo;
}

It's very clear what the intention of the code is.

很清楚代码的用意是什么。