0

I was wondering if there is a complexity and time difference when doing these two operations:

1)

int sum = 0;
for (int i = 0; i < 1000000; i++) {
    sum = sum + i;
}

2)

int sum = 0;
for (int i = 0; i < 1000000; i++) {
    sum += i;
}

or maybe image the problem to be bigger numbers/data, this is just an example.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
TheYaINN
  • 114
  • 10

2 Answers2

1

There is a difference in priority, compound assignment sum += i is less primary than assignment and addition sum = i + 1. Incrementation i++ is even more primary.

for more information : operator precedence

Loan
  • 142
  • 1
  • 16
  • 3
    The priority seems irrelevant in the context of this question. – Mark Rotteveel Jan 31 '19 at 09:51
  • the more important thing than precedence is that [`+=` doesn't require a cast](https://stackoverflow.com/q/8710619/995714), but that's also irrelevant here – phuclv Jan 31 '19 at 12:46
1

These variants are the same from performance point of view (both will be as iadd instruction in java bytecode)

But sum += 1 replaced with sum = (int) (sum + 1) And it has differrens for types like byte or short for compilation E.g. this code will be compiled

byte i = 0;
for(int j = 0; j < 10; j++) {
    i += j; //i = (byte) (i + j)
}

but you will get compilation error for code

byte i = 0;
for(int j = 0; j < 10; j++) {
    i = i + j;
}
Andrey
  • 464
  • 3
  • 5