C# for和foreach两种循环的效率问题

190 阅读1分钟

所谓的效率就是哪个运行的比较快,
用来循环数组类的一般使用for或者foreath
下面通过代码测试他们的效率:


创建一个int类型数组使用3种循环查看效率:

for

int[] a = new int[1000000000];
 Stopwatch b = new Stopwatch();
  b.Start();
for (int i = 0; i <= a.Length; i++) 
 {                    
 }
b.Stop();                  
Console.WriteLine(b.Elapsed);

在这里插入图片描述

foreach:

int[] a = new int[1000000000];
 Stopwatch b = new Stopwatch();
b.Start();
foreach (int i in a)
{ 
 }
 b.Stop();                  
Console.WriteLine(b.Elapsed);

在这里插入图片描述

while:

基本不会使用这种方法…

int[] a = new int[1000000000];
Stopwatch b = new Stopwatch();
  b.Start();
 int i =0;
 while (i <= a.Length)
  {
    i++;
   }
b.Stop();                  
 Console.WriteLine(b.Elapsed);

在这里插入图片描述
总结:
还测试了其他的…
测试了五六次for和while的速度确实比foreath快一点,
不过处理小数据用哪种都差不多速度都不会太远,

纯手打,点个赞呗~