Reputation: 7193
I read somewhere that:
Good Practice: exp += val
Bad Practice: exp = exp + val
The second options forces the JIT to evaluate both copies of exp
, and many times this is not needed. The first statement can be optimized far better than the second, since the JIT can avoid evaluating the exp twice.
So I wrote a sample test to verify this. But I am getting a result that I can conclude something. Can anyone help me out to understand if above one is good or bad practice OR I have any bug in my example.
static void Main(string[] args)
{
DateTime startTime;
DateTime endTime;
for (int run = 0; run < 10; run++)
{
Console.WriteLine("--- Run #" + run.ToString());
long sumB = 0;
startTime = DateTime.Now;
for (long i = 0; i < 1000000000; i++)
{
sumB = sumB + 2L;
}
endTime = DateTime.Now;
Console.WriteLine(endTime - startTime);
long sumA = 0;
startTime = DateTime.Now;
for (long j = 0; j < 1000000000; j++)
{
sumA += 2L;
}
endTime = DateTime.Now;
Console.WriteLine(endTime - startTime);
}
Console.WriteLine("*");
Console.ReadKey();
}
Upvotes: 1
Views: 138
Reputation: 171178
a += b
only evaluates each expression once while
a = a + b
evaluates a twice. a
might be an expensive expression (not a local variable):
int[] GetArray() { return new int[100000]; }
GetArray()[0] += 1;
is very different from
GetArray()[0] = GetArray()[0] + 1;
and in this case semantically different but that's not the point. Just assume that GetArray
is expensive.
This is a rare case though and I'm only saying because you asked about performance. Normally, you'd write the compound assignment form purely for stylistics reasons which are subjective.
And for fun we can look under the hood how that array example even works. The C# compiler will emit IL that computes a managed pointer (an "interior pointer") to the given array element, then it will evaluate the right hand side, that it stores the result using the pointer into the array.
Surprisingly, at the IL level managed pointers are commonplace. C# shields you from it.
Upvotes: 2
Reputation: 254461
In C++ at least (I don't know C#), a += b
will only evaluate a
once, while a = a + b
will evaluate it twice.
If it's a complicated expression, then that could have a performance impact. If, as in your example, it's a simple variable (or, more generally, an expression that the compiler can prove has no side effects), then both should be optimised to produce the same code, so there's likely to be no significant difference.
Better advice would be to favour a += b
because it avoids redundancy, helping readability and reducing the scope for errors, rather than using (often spurious or irrelevant) arguments about performance.
Upvotes: 5