Should I really care if I am using i++
, ++i
or i += 1
in a loop?
Short answer is that there is no difference. Continue reading for the long answer.
So, again, what is the difference between these statements?
Let us use dnSpy and dissassembly to look at the facts.
Starting with i++
. In dnSpy this generates following Common Intermediate Language (CIL):
ldloc.0
ldc.i4.1
add
stloc.0
Looking at the dissassembly this gives:
mov eax,dword ptr [rbp+2Ch]
inc eax
mov dword ptr [rbp+2Ch],eax
Onto ++i
. In dnSpy this generates following identical CIL:
ldloc.1
ldc.i4.1
add
stloc.1
with identical assembly code:
mov eax,dword ptr [rbp+28h]
inc eax
mov dword ptr [rbp+28h],eax
Same thing for i += 1
- CIL:
ldloc.2
ldc.i4.1
add
stloc.2
Assembly:
mov eax,dword ptr [rbp+24h]
inc eax
mov dword ptr [rbp+24h],eax
So what does this give us in a loop:
for (i = 0; i < 100; i++)
{
k += i;
}
This results in following assembly (for all 3 cases):
xor edx,edx
add eax,edx
inc edx
cmp edx,64h
jl Increment.Program.Main(System.String[]) + 010h(07FFADDF734D0h)
Conclusion: No matter what your mama says, there is no practical difference between i++, ++i or i += 1.
Just use the one you like best...