Declaring a variable inside or outside an foreach loop: which is faster/better?

前端 未结 10 1774
灰色年华
灰色年华 2020-11-27 14:58

Which one of these is the faster/better one?

This one:

List list = new List();
User u;

foreach (string s in l)
{
    u = new         


        
相关标签:
10条回答
  • 2020-11-27 15:32

    There should be no percievable difference in performance.

    0 讨论(0)
  • 2020-11-27 15:33

    I went to verify this issue. Suprisingly finding out at my dirty tests that the 2nd option is even slightly faster all the time.

    namespace Test
    {
      class Foreach
      {
        string[] names = new[] { "ABC", "MNL", "XYZ" };
    
        void Method1()
        {
          List<User> list = new List<User>();
          User u;
    
          foreach (string s in names)
          {
            u = new User();
            u.Name = s;
            list.Add(u);
          }
        }
    
        void Method2()
        {
    
          List<User> list = new List<User>();
    
          foreach (string s in names)
          {
            User u = new User();
            u.Name = s;
            list.Add(u);
          }
        }
      }
    
      public class User { public string Name; }
    }
    

    I verified the CIL but it is not identical.

    So I prepared something what I wanted to be much better test.

    namespace Test
    {
      class Loop
      { 
    
        public TimeSpan method1 = new TimeSpan();
        public TimeSpan method2 = new TimeSpan();
    
        Stopwatch sw = new Stopwatch();
    
        public void Method1()
        {
          sw.Restart();
    
          C c;
          C c1;
          C c2;
          C c3;
          C c4;
    
          int i = 1000;
          while (i-- > 0)
          {
            c = new C();
            c1 = new C();
            c2 = new C();
            c3 = new C();
            c4 = new C();        
          }
    
          sw.Stop();
          method1 = method1.Add(sw.Elapsed);
        }
    
        public void Method2()
        {
          sw.Restart();
    
          int i = 1000;
          while (i-- > 0)
          {
            var c = new C();
            var c1 = new C();
            var c2 = new C();
            var c3 = new C();
            var c4 = new C();
          }
    
          sw.Stop();
          method2 = method2.Add(sw.Elapsed);
        }
      }
    
      class C { }
    }
    

    Also in this case 2nd method was always winning but then I verified the CIL finding no difference.

    I am not CIL-reading guru but I see no decleration issue. As was already pointed out declaration is not allocation so there is no performance penalty on it.

    Test

    namespace Test
    {
      class Foreach
      {
        string[] names = new[] { "ABC", "MNL", "XYZ" };
    
        public TimeSpan method1 = new TimeSpan();
        public TimeSpan method2 = new TimeSpan();
    
        Stopwatch sw = new Stopwatch();
    
        void Method1()
        {
          sw.Restart();
    
          List<User> list = new List<User>();
          User u;
    
          foreach (string s in names)
          {
            u = new User();
            u.Name = s;
            list.Add(u);
          }
    
          sw.Stop();
          method1 = method1.Add(sw.Elapsed);
        }
    
        void Method2()
        {
          sw.Restart();
    
          List<User> list = new List<User>();
    
          foreach (string s in names)
          {
            User u = new User();
            u.Name = s;
            list.Add(u);
          }
    
          sw.Stop();
          method2 = method2.Add(sw.Elapsed);
        }
      }
    
      public class User { public string Name; }
    
    0 讨论(0)
  • 2020-11-27 15:35

    Whenever you've a question about performance, the only thing to do is measure - run a loop around your test and time it.

    To answer your question - without measuring :-) or looking at the generated ilasm - any difference wouldn't be noticeable in a meaningful number of iterations and the most expensive operation in your code there is likely to be the user allocation by a few orders of magnitude, so concentrate on code clarity (as you should in general) and go with 2.

    Oh, its late and I guess I'm just trying to say don't worry about this sort of thing or get caught up in details like this.

    K

    0 讨论(0)
  • 2020-11-27 15:38

    Technically, the first example will save a few nanoseconds because the stack frame will not have to be moved to allocate a new variable, but this is such a tiny amount of CPU time you won't notice it, that's if the compiler doesn't optimize any difference away anyays.

    0 讨论(0)
提交回复
热议问题