日期:2014-05-18  浏览次数:20765 次

嘿嘿!!奇怪了for比foreach快?????
using System;
using System.Diagnostics;
class Test
{
  static void Main()
  {
  int[] lists = Method();
  Stopwatch stop = new Stopwatch();
  stop.Start();
  for (int i = 0; i < lists.Length; i++)
  {

  }
  Console.WriteLine(stop.ElapsedMilliseconds);
  stop.Reset();
  stop.Start();
  foreach (int a in lists)
  {

  }
  Console.WriteLine(stop.ElapsedMilliseconds);
  Console.ReadKey();
  }
  static int[] Method()
  {
  int[] ints = new int[10000000];
  for (int i = 0; i < 10000000; i++)
  {
  ints[i] = i + 1;
  }
  return ints;
  }
}

33
62



------解决方案--------------------
奇怪吗?
------解决方案--------------------
foreach需要调用IEnumerator,IEnumerable接口

------解决方案--------------------
.
------解决方案--------------------
有老帖讨论过
------解决方案--------------------
是的.
------解决方案--------------------
...
ArrayList list=new ArrayList();
list.Add(1);
list.Add("a");
list.Add("vb");

foreach(strig c in list)
{
c=c.SubString(1);
}

for(int i=0;i<list.count;i++)
{
object o=list[i];
if(object.GetType()==typeof(string))
{
string c=(string)o;
c=c.SubString(1); 
}
}
------解决方案--------------------
Effective C#上有专门介绍for和foreach的区别的
------解决方案--------------------
我个人比较偏向于foreach
虽然有的时候for比foreach快
但是大多数foreach效率都要好些
而且foreach的代码更加简练

看看这个吧

http://www.cnblogs.com/WuCountry/archive/2007/02/27/658710.html
------解决方案--------------------
我昏迷……for里面是个空的,有啥可比性?

就是吧i自增到lists.Length而已,说不定还被编译器优化了……