for的效率测试和结果,分享一下之前一直认为for (int i 0, h arr.Count i h i++)和for (int i 0
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[],两者效率基本差不多
测试代码:
C# code
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());}