12

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?

erencan
  • 3,725
  • 5
  • 32
  • 50
Robert
  • 10,403
  • 14
  • 67
  • 117
  • Yes, I just thinking, but is correct and in the end is better to use +=. Thanks @Trobbins – Robert Apr 23 '15 at 17:38
  • 2
    @Trobbins That's in a way saying the opposite. Using `a = a + b` is more type-safe than `a += b`. Anyways, I think it's considered better simply as it's shorter. – Bubletan Apr 23 '15 at 17:40
  • To answer the other part of your question: Performance wise at the instruction level, `sum += i` is better than `sum = sum + i`. –  Apr 23 '15 at 17:40
  • @I.K. I don't think so. There wouldn't be any performance difference between them. – Rohit Jain Apr 23 '15 at 17:41
  • `sum += i` means you have an implicit cast to the type of sum. This can also be seen as a disadvantage. Generally spoken, hidden type consersions can be dangerous because you don't immediately see that it is happening. – Trinimon Apr 23 '15 at 17:42
  • @RohitJain, it is. The former is 1 instruction whereas the latter is 3 instructions. –  Apr 23 '15 at 17:43
  • @I.K. There is no instruction for `+=` operator in [JVM instruction set](https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html#jvms-2.11.1-220). So, no it can't be just 1 instruction. – Rohit Jain Apr 23 '15 at 17:44
  • @RohitJain, for some reason I thought it had. I stand corrected. Thanks for the info. –  Apr 23 '15 at 17:48
  • @Rohit, In the specific case of int typed local variables incremented by a small constant, there actually is a shorthand instruction in the bytecode (`iinc`). However, there shouldn't be any performance difference since it's JITed anyway and even in interperted mode the difference would be negligible. – Antimony Apr 24 '15 at 01:14
  • It will make a difference for `array[veryLongComputation()] += value` – Holger Apr 24 '15 at 11:08

3 Answers3

11

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.

erencan
  • 3,725
  • 5
  • 32
  • 50
  • I reproduced and got the same result. Although we are not quite sure **why** the book is saying it is better to use the concise syntax. The OP never stated the book's reason. –  Apr 23 '15 at 18:10
  • 2
    very interesting. do the same for int i and double sum, is it still the same? or double i and int sum, there you should see the difference – maraca Apr 23 '15 at 18:45
  • Please add " **assuming that both compile** " to your second sentence, otherwise it's wrong (see ericbn's answer). – maaartinus Apr 23 '15 at 23:00
  • i am not assuming to compile. I have already compiled both files. see my edits. @maaartinus – erencan Apr 24 '15 at 07:04
  • For both types being the same, you're right. But with `double i = 1; int sum = 2;`, the expression `sum = sum + i` misses a cast. – maaartinus Apr 24 '15 at 11:09
5

As @Trinimon commented, there's a difference between += and + operators:

E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once. (§15.26.2 Compound Assignment Operators)

So

int sum = 0;
sum += 1.0; // this is equivalent to sum = (int) (sum + 1.0);
sum = sum + 1.0; // this will not compile
                 // incompatible types: possible lossy conversion from double to int

Contrary to common sense, it is safer not to use the += operator then.

Good question!

Reference

Java's +=, -=, *=, /= compound assignment operators

Community
  • 1
  • 1
ericbn
  • 10,163
  • 3
  • 47
  • 55
  • OP do not ask for implicit casting in `+=` operator, since we can assume the statement in the question will compile. We can assume that both variabes have the same type. However, your answer pays attention to a good point. – erencan Apr 24 '15 at 07:08
  • @erencan, he's asking "Why is better to use `+=` operator?" and I'm pointing the difference. If we "assume that both variables have the same type" then using the `+` (instead `+=`) operator will guarantee the assumption is right (while using `+=` will not). – ericbn Apr 24 '15 at 12:56
1

There is no performance difference. One way might read slightly better.

It could be argued sum += i; is better style because it is not as redundant, it may take slightly less work for a reader to figure out what's going on with += because it's not necessary to look for sum on both sides of the assignment operator.

"Best practices" exist at least as much for readability and maintainability concerns as they do for performance, don't assume everything is about performance.

Using += in some obscure cases involving implicit casts may be problematic. There is a Java puzzler (from the Bloch and Gafter book) that manages to misuse this, see this question.

Community
  • 1
  • 1
Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276