int i = 0;
i += 1;
i = i + 1;
What is the difference between these 2 options? What changes in performance time terms? Which is the most powerful?
int i = 0;
i += 1;
i = i + 1;
What is the difference between these 2 options? What changes in performance time terms? Which is the most powerful?
+= does implicit casting. For example this will compile:
int i = 0;
i += 1L;
And this will not:
int i = 0;
i = i + 1L;
Tried to compile both snippets with my jdk1.8.0_11 on Windows 8 and see bytecode difference...
0: iconst_0
1: istore_1
2: iinc 1, 1
for i += 1
version, and:
0: iconst_0
1: istore_1
2: iload_1
3: iconst_1
4: iadd
5: istore_1
for i = i + 1
version.
So the conclusion is: you may indeed get different bytecode (or may not, see @TDG answer) and different performance, but the difference is insignificant compared to other overheads your programs will have.
You have to think in terms of the assembly code generated and what assembly code generated is completely dependent on what compiler is being used. Some compilers will make these differences non existent as they will performance tune your statements. However in general...
i += 1;
Is slightly more efficient than..
i = i + 1;
because the address of "i" is only accessed once in "i += 1". It saves you one assembly operation which is usually not a big deal unless your computation might be done through many iterations. It results in saving you an assembly "mov" instruction.
The Byte Code
of the next two "programs":
//first "program"
int i = 0;
i = i + 1;
//second program
int i = 0;
i += 1;
is the same:
0: iconst_0
1: istore_1
2: iinc 1, 1
5: return
And when decompiling the above Byte Code
we get this -
int i = 0;
++i;
so it does not matter which one you use.
EDIT The above was tested on jdk1.7.0_79 and Eclipse 3.8.2.
i=i+1;
it will have to load the value of i, add one to it, and then store the result back to i
i+=1;
add one to it, and then store the result
EDIT 1: some people say that the second (i+=1) is more faster, but if you make disassembly this part code in see C++(vs 2013), you can see that they are the same. Unfortunately, I don not know how to make this in JAVA.
i = i + 1;
00AF52C5 mov eax,dword ptr [i]
00AF52C8 add eax,1
00AF52CB mov dword ptr [i],eax
i +=1;
00AF52CE mov eax,dword ptr [i]
00AF52D1 add eax,1
00AF52D4 mov dword ptr [i],eax