我去验证了这个问题。出乎意料的是,在我的肮脏测试中,发现第二个选项始终比以前稍快一些。
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 { }
}
同样在这种情况下,第二种方法始终是赢家,但后来我验证了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; }