Is there any performance difference with ++i vs i += 1 in C#?

岁酱吖の 提交于 2020-11-29 07:29:50

问题


i += a should be equivalent to i = i + a. In the case where a == 1, this is supposedly less efficient as ++i as it involves more accesses to memory; or will the compiler make it exactly the same as ++i?


回答1:


It is easy to answer: the C# compiler translates C# source code to IL opcodes. There is no dedicated IL opcode that performs the equivalent of the ++ operator. Which is easy to see if you look at the generated IL with the ildasm.exe tool. This sample C# snippet:

        int ix = 0;
        ix++;
        ix = ix + 1;

Generates:

  IL_0000:  ldc.i4.0               // load 0
  IL_0001:  stloc.0                // ix = 0

  IL_0002:  ldloc.0                // load ix
  IL_0003:  ldc.i4.1               // load 1
  IL_0004:  add                    // ix + 1
  IL_0005:  stloc.0                // ix = ix + 1

  IL_0006:  ldloc.0                // load ix
  IL_0007:  ldc.i4.1               // load 1
  IL_0008:  add                    // ix + 1
  IL_0009:  stloc.0                // ix = ix + 1

It generates the exact same code. Nothing the jitter can do but generate machine code that is equally fast.

The pre/post increment operator is syntax sugar in C#, use it wherever it makes your code more legible. Or perhaps more relevant: avoid it where it makes it less legible. They do have a knack for letting you create expressions that have too many side-effects.




回答2:


The compiler should optimise the code whichever way you write it so I believe i = i + 1 is the same as ++i.




回答3:


I don't think there will be any difference, but You can put it in action, something like:

class Program
{
    static void Main(string[] args)
    {
        //Add values
        List<objClass> lst1 = new List<objClass>();
        for (int i = 0; i < 9000000; i++)
        {
            lst1.Add(new objClass("1", ""));
        }

        //For loop ++i
        DateTime startTime = DateTime.Now;
        for (int i = 0; i < 9000000; ++i)
        {
            lst1[i]._s1 = lst1[i]._s2;
        }
        Console.WriteLine((DateTime.Now - startTime).ToString());

        //For loop i+=1
        startTime = DateTime.Now;
        for (int i = 0; i < 9000000; i+=1)
        {
            lst1[i]._s1 = lst1[i]._s2;
        }
        Console.WriteLine((DateTime.Now - startTime).ToString());

    }
public class objClass
    {
        public string _s1 { get; set; }
        public string _s2 { get; set; }

        public objClass(string _s1, string _s2)
        {
            this._s1 = _s1;
            this._s2 = _s2;
        }
    }

}



回答4:


It depends. In theory, given a sufficiently naive compiler, ++x might well be more efficient than x += 1.

However, I don't know of such a naive compiler.

  • if the value of the operand is known at compile-time, then the compiler can optimize the operation.
  • if the value can be determined to be constant at run-time, then JIT compiler can optimize the operation as well.

Moreover, modern CPUs are highly complex beasts, which can execute a lot of operations in parallel, and quite often, "simple" operations like these can be entirely hidden by running them in parallel with larger, more complex ones.

A good rule of thumb, when optimizing and just when writing in general is to express your intent as clearly as possible.

That makes it easier for other programmers to read your code, but it also makes it easier for the compiler to do so.

If you want to increment a value, use the increment operator (++), because it describes exactly what you want to do.

If you want to add a variable or unknown value, use the += operator, because that is what it's for.

If you're clear about your intentions, then the compiler gets more information about your code, and can optimize accordingly.

If you write x += 1, you're really trying to trip up the compiler. You're saying "use the general-purpose addition operator to add one to x". Then the compiler has to figure out "ok, you said to use general-purpose addition, but I can see that's nto necessary, so I'm just going to increment instead". You could have told it that. Now, instead, you have to rely on the compiler being clever.




回答5:


Unless a is defined a const int == 1 how can the compiler know at compile time that a == 1?

So the answer must be no, the compiler cannot compile this to ++i.



来源:https://stackoverflow.com/questions/6889647/is-there-any-performance-difference-with-i-vs-i-1-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!