C# for VS foreach 性能对比

string[] strs = new string[10000];
for (int i = 0; i < 10000; i++)
{
strs[i] = i.ToString();
}


string temp1 = "";
string temp2 = "";
long fortime = 0;
long foreachtime = 0;
timer.Reset();
timer.Start();

for (int i = 0; i < 10000; i++)
{
temp1 = strs[i];
}
fortime = timer.ElapsedTicks;
timer.Stop();

timer.Reset();

timer.Start();
foreach (string str in strs)
{
temp2 = str;
}
foreachtime = timer.ElapsedTicks;
timer.Stop();


MessageBox.Show(string.Format("for Time:{0} result {1},foreach Time:{2} result{3}", fortime, temp1, foreachtime, temp2));

以上代码 就是我测试的代码 我的电脑 上测下来是

for 的速度要比foreach快40ms左右。

那么下次大家选择的时候 如果性能很重要的话 就完全可以放心地选择for语句了

当然foreach 也有其自身的方便之处,比如有些 XXCollection 类型 用for没法索引,最好的办法就是用 foreach了

原文地址:https://www.cnblogs.com/SHGF/p/2338992.html