Arvind Sasikumar
Arvind Sasikumar

Reputation: 502

Is ternary operator less efficient than an if statement that sets a different value to a variable

Example 1:

a = a > b ? b : a

Example 2:

if (a > b)
    a = b

While the difference may not be much, I'm thinking example 2 is computationally more efficient, as in example 1, if a < b, the same value of a is still put inside the variable a which is an unnecessary operation, one that's avoided in the if statement.

On the other hand, I'm thinking maybe the compiler understands this and both statements work with same efficiency post compilation because they correspond to the same instructions?

Upvotes: 2

Views: 581

Answers (1)

Giorgi Tsiklauri
Giorgi Tsiklauri

Reputation: 11136

In your case, your ternary operation and your if statement are not the same, since you don't have an else statement after if, so it only checks whether a>b.

If you are interested in the question about the performance difference in case of semantically equal Ternary operation and if-else block, then the answer is No, there is no much of the difference. Ternary Operator is just a syntactic sugar of writing if-else.

Here is the bytecode comparison in the simplest Java program, with only one (an entry-point) main method, where in first case I implement Ternary Operator, and in the second one - if-else statement.

 //First example, having Ternary Operator
  public static void main(java.lang.String[]);
    Code:
       0: iconst_0
       1: istore_1
       2: iconst_1
       3: istore_2
       4: iload_1
       5: iload_2
       6: if_icmple     13
       9: iload_2
      10: goto          14
      13: iload_1
      14: istore_1
      15: return
}

//Second Example, having if-else alternative
  public static void main(java.lang.String[]);
    Code:
       0: iconst_0
       1: istore_1
       2: iconst_1
       3: istore_2
       4: iload_1
       5: iload_2
       6: if_icmple     14
       9: iload_2
      10: istore_1
      11: goto          16
      14: iload_1
      15: istore_1
      16: return
}

Upvotes: 3

Related Questions