Search code examples
javaperformancesyntaxoperatorsbytecode

java best practices using += operator


I was reading a book "Beginning Java 8 Fundamentals". And I saw this line:

//some code...
sum = sum + i; // Better to use sum += i
//more code...

Then here is my doubt: Is that true? Why is better to use += operator? I thought that += operator was only a more simplified expression? If I use one or other which implications there are in the code performance?


Solution

  • I think, the book offers to use += as best practice. Indeed, there is no difference between 2 statements of sum += i and sum = sum + i

    I implement 2 classes each include one statement and watch the byte code with command javap

    Here is program 1:

    public class Program1 {
         public static void main(String []args) {
            int i = 1;
            int sum = 2;
            sum += i;
         }
    }
    

    Here is the byte code:

    public class Program1 {
      public Program1();
        Code:
           0: aload_0
           1: invokespecial #1                  // Method java/lang/Object."<init>":()V
           4: return
    
      public static void main(java.lang.String[]);
        Code:
           0: iconst_1
           1: istore_1
           2: iconst_2
           3: istore_2
           4: iload_1
           5: iload_2
           6: iadd
           7: istore_1
           8: return
    }
    

    Here is program 2:

    public class Program2 {
        public static void main(String []args) {
            int i = 1;
            int sum = 2;
            sum = sum + i;
        }
    }
    

    Here is the byte code:

    public class Program2 {
      public Program2();
        Code:
           0: aload_0
           1: invokespecial #1                  // Method java/lang/Object."<init>":()V
           4: return
    
      public static void main(java.lang.String[]);
        Code:
           0: iconst_1
           1: istore_1
           2: iconst_2
           3: istore_2
           4: iload_1
           5: iload_2
           6: iadd
           7: istore_1
           8: return
    }
    

    As seen above, the byte codes are the same, so the statements are the same. No difference.

    Edit 1: How to run javap command

    1. Save Program1.java to a java file
    2. Compile the code. Run javac Program1.java
    3. Both Program1 and Program2 should be compile successfully.
    4. Run javap -c Program1.class to see the bytecode.

    Edit 2: The difference between operators if the variable types are different

    += operator has an implicit cast to left operant, so if the variables differ in its types += operator wil automaticaly cast.

    Here is the code

    long i = 1;
    int sum = 2;
    sum += i; //means sum = (int)(i + sum)
    

    Furthermore, sum = sum + i do not have implicit cast, this statement will not compile.

    I generaly use explicit casting, if there is need to cast. This make the code more readable and safe.