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
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
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);
}
}
虽然有的时候for比foreach快
但是大多数foreach效率都要好些
而且foreach的代码更加简练看看这个吧http://www.cnblogs.com/WuCountry/archive/2007/02/27/658710.html