How += is more optimized that normal expression

Paw*_*anS 1 .net c# optimization

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();
    }
Run Code Online (Sandbox Code Playgroud)

Mik*_*our 5

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.