I\'m under the impression that these two commands result in the same end, namely incrementing X by 1 but that the latter is probably more efficient.
If this is not c
I wrote a simple console app:
static void Main(string[] args)
{
int i = 0;
i += 1;
i = i + 1;
Console.WriteLine(i);
}
I disassembled it using Reflector and here's what i got:
private static void Main(string[] args)
{
int i = 0;
i++;
i++;
Console.WriteLine(i);
}
They are the same.
Back in the early 1980s, one of the really cool optimizations of the Lattice C Compiler was that "x = x + 1;", "x += 1;" and "x++;" all produced exactly the same machine code. If they could do it, a compiler written in this millenium should definitely be able to do it.
If x is a simple integer scalar variable, they should be the same.
If x is a large expression, possibly with side effects, +=1
and ++
should be twice as fast.
Many people concentrate on this kind of low-level optimization as if that's what optimization is all about. I assume you know it's a much bigger subject.
Something worth noting is that +=, -=, *= etc. do an implicit cast.
int i = 0;
i = i + 5.5; // doesn't compile.
i += 5.5; // compiles.
are the same.
x=x+1
is mathematical seen a contradiction whereas
x+=1
isn't and is light to be typed.
On x86, if x is in register eax, they will both result in something like
inc eax;
So you're right, after some compilation stage, the IL will be the same.
There's a whole class of questions like this that can be answered with "trust your optimizer."
The famous myth is that
x++;
is less efficient than
++x;
because it has to store a temporary value. If you never use the temporary value, the optimizer will remove that store.