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

后端 未结 5 657
半阙折子戏
半阙折子戏 2021-01-19 12:42

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 mak

5条回答
  •  心在旅途
    2021-01-19 13:18

    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 lst1 = new List();
            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;
            }
        }
    
    }
    

提交回复
热议问题