ฉันไปตรวจสอบปัญหานี้ น่าแปลกใจที่พบว่าการทดสอบสกปรกของฉันที่ตัวเลือกที่ 2 นั้นเร็วกว่าเล็กน้อยตลอดเวลา
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; }
}
ฉันตรวจสอบ CIL แล้ว แต่ไม่เหมือนกัน

ดังนั้นฉันจึงเตรียมบางสิ่งที่ฉันต้องการจะทดสอบได้ดีกว่ามาก
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 { }
}
นอกจากนี้ในกรณีนี้วิธีที่ 2 มักจะชนะ แต่แล้วฉันก็ตรวจสอบ CIL แล้วว่าไม่พบความแตกต่าง

ฉันไม่ใช่กูรูด้านการอ่าน CIL แต่ฉันไม่เห็นปัญหาความเสื่อม ตามที่ได้ชี้ไปแล้วว่าการประกาศไม่ใช่การจัดสรรดังนั้นจึงไม่มีการลงโทษด้านประสิทธิภาพ
ทดสอบ
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; }