c# for foreach执行效率比较

一直不了解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 < iCount; 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 < iCount; 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 < iCount; 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循环的效率高 如有异议 欢迎讨论。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值