c# for 代码测试

之前一直认为
for (int i = 0, h = arr.Count; i < h; i++)

for (int i = 0; i < arr.Count; i++)
两种写法,在C#里应该是差不多的,今天突然有人问,就写了个程序测试了一下,结果出乎我的意料
如果arr是List<T>,前者的效率比后者高大约一倍,如果arr是string[],两者效率基本差不多

测试代码如下 

 

int tnum = 100000; // 添加或查找的次数
            int outnum = 10; // 外层循环次数
            List<string> arr = new List<string>();
            for (int i = 0; i < tnum; i++)
                arr.Add(i.ToString());
            string[] arr2 = new string[tnum];
            for (int j = 0; j < outnum; j++)
            {
                Stopwatch watch = new Stopwatch();
                string msg;
                msg = "Number ";
                watch.Reset();
                watch.Start();
                for (int i = 0, h = arr.Count; i < h; i++)
                {
                }
                watch.Stop();
                Console.WriteLine(msg + "耗时:" + watch.ElapsedTicks.ToString());
                msg = ".Count ";
                watch.Reset();
                watch.Start();
                for (int i = 0; i < arr.Count; i++)
                {
                }
                watch.Stop();
                Console.WriteLine(msg + "耗时:" + watch.ElapsedTicks.ToString());
                msg = "Length ";
                watch.Reset();
                watch.Start();
                for (int i = 0; i < arr2.Length; i++)
                {
                }
                watch.Stop();
                Console.WriteLine(msg + "耗时:" + watch.ElapsedTicks.ToString());
            }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值