Search code examples
javaperformancevariablesvariable-assignmentternary

Using Java's ternary operator, what's the implication of assigning a variable to itself?


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 (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.


Solution

  • 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.

    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 (foo != null) {
        bar = foo;
    }
    

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