Does the Java compiler optimize an unnecessary ternary operator?

  • A+
Category:Languages

I’ve been reviewing code where some coders have been using redundant ternary operators “for readability.” Such as:

boolean val = (foo == bar && foo1 != bar) ? true : false; 

Obviously it would be better to just assign the statement’s result to the boolean variable, but does the compiler care?

 


This can be tested by comparing the bytecodes as compiled by the JVM.
I created a mock class to illustrate this:

Case I (without the ternary operator):

class Class {      public static void foo(int a, int b, int c) {         boolean val = (a == c && b != c);         System.out.println(val);     }      public static void main(String[] args) {        foo(1,2,3);     } } 

Case II (with the ternary operator):

class Class {      public static void foo(int a, int b, int c) {         boolean val = (a == c && b != c) ? true : false;         System.out.println(val);     }      public static void main(String[] args) {        foo(1,2,3);     } } 

Bytecode for foo() method in Case I:

       0: iload_0        1: iload_2        2: if_icmpne     14        5: iload_1        6: iload_2        7: if_icmpeq     14       10: iconst_1       11: goto          15       14: iconst_0       15: istore_3       16: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;       19: iload_3       20: invokevirtual #3                  // Method java/io/PrintStream.println:(Z)V       23: return 

Bytecode for foo() method in Case II:

       0: iload_0        1: iload_2        2: if_icmpne     14        5: iload_1        6: iload_2        7: if_icmpeq     14       10: iconst_1       11: goto          15       14: iconst_0       15: istore_3       16: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;       19: iload_3       20: invokevirtual #3                  // Method java/io/PrintStream.println:(Z)V       23: return 

Note that in both cases the bytecode is identical, i.e the compiler disregards the ternary operator when compiling the value of the val boolean.

That being said, I find that unnecessary usage of the ternary operator tends to make the code more confusing and less readable, contrary to the original intention.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: