作者:手机用户2502909581 | 来源:互联网 | 2023-09-25 12:29
一直不了解for foreach执行效率 特写了以下一段代码进行测试。
代码如下:
DateTime dt5 = DateTime.Now;
ArrayList a = new ArrayList();
Random r = new Random();
for (int i = 0; i <10000000; i++)
{
a.Add("string" + r.Next().ToString());
}
DateTime dt6 = DateTime.Now;
TimeSpan ts3 = dt6 - dt5;
label9.Text = ts3.TotalMilliseconds.ToString();
int iCount = a.Count;
DateTime dt1 = DateTime.Now;
foreach (string s in a)
{
}
DateTime dt2 = DateTime.Now;
TimeSpan ts1 = dt2 - dt1;
label2.Text = ts1.TotalMilliseconds.ToString();
dt1 = DateTime.Now;
foreach (string s in a)
{
}
dt2 = DateTime.Now;
ts1 = dt2 - dt1;
label3.Text = ts1.TotalMilliseconds.ToString();
dt1 = DateTime.Now;
foreach (string s in a)
{
}
dt2 = DateTime.Now;
ts1 = dt2 - dt1;
label4.Text = ts1.TotalMilliseconds.ToString();
StringBuilder sb2 = new StringBuilder();
DateTime dt3 = DateTime.Now;
for (int i = 0; i {
string s = a[i] as string;
}
DateTime dt4 = DateTime.Now;
TimeSpan ts2 = dt4 - dt3;
label6.Text = ts2.TotalMilliseconds.ToString();
sb2 = new StringBuilder();
dt3 = DateTime.Now;
for (int i = 0; i {
string s = a[i] as string;
}
dt4 = DateTime.Now;
ts2 = dt4 - dt3;
label7.Text = ts2.TotalMilliseconds.ToString();
sb2 = new StringBuilder();
dt3 = DateTime.Now;
for (int i = 0; i {
string s = a[i] as string;
}
dt4 = DateTime.Now;
ts2 = dt4 - dt3;
label8.Text = ts2.TotalMilliseconds.ToString();
代码可以从下载地址http://download.csdn.net/detail/devgis/6987203
for foreach对同一arraylist对象进行1000万次操作进行比较 结果如下
通过比较发现for循环的效率高 如有异议 欢迎讨论。
c# for foreach执行效率比较,布布扣,bubuko.com