关于For与Foreach的区别,博客园里已经有好多这样文章了,都分析的挺好:http://www.cnblogs.com/jobs/archive/2004/07/17/25218.aspx  不过里面关于安全部分的描述可以略过。

以下是我的测试代码:

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Diagnostics; namespace ConApp_PerformanceTest
{
class Program
{
static void Main(string[] args)
{
string[] timeperiod = new string[10];
timeperiod[0] += "testArrayListWithFor ";
timeperiod[1] += "testArrayListWithForEach";
timeperiod[2] += "testArrayWithFor ";
timeperiod[3] += "testArrayWithForEach ";
timeperiod[4] += "testListWithForEach ";
timeperiod[5] += "testListWithFor ";
for (int i = 0; i < 6; i++)
{
Stopwatch sw = new Stopwatch();
TestData td = new TestData();
sw.Reset();
sw.Start();
td.testArrayListWithFor();
sw.Stop();
timeperiod[0] += " " + sw.ElapsedMilliseconds.ToString("00000"); sw.Reset();
sw.Start();
td.testArrayListWithForEach();
sw.Stop();
timeperiod[1] += " " + sw.ElapsedMilliseconds.ToString("00000"); sw.Reset();
sw.Start();
td.testArrayWithFor();
sw.Stop();
timeperiod[2] += " " + sw.ElapsedMilliseconds.ToString("00000"); sw.Reset();
sw.Start();
td.testArrayWithForEach();
sw.Stop();
timeperiod[3] += " " + sw.ElapsedMilliseconds.ToString("00000"); sw.Reset();
sw.Start();
td.testListWithForEach();
sw.Stop();
timeperiod[4] += " " + sw.ElapsedMilliseconds.ToString("00000"); sw.Reset();
sw.Start();
td.testListWithFor();
sw.Stop();
timeperiod[5] += " " + sw.ElapsedMilliseconds.ToString("00000");
}
Console.Clear();
for (int i = 0; i < 10; i++)
Console.WriteLine(timeperiod[i]);
Console.Read(); }
} class TestData
{
public TestData()
{
}
public void testArrayListWithFor()
{
ArrayList sa;
object ss;
sa = new ArrayList();
for (int i = 0; i < 10000000; i++)
sa.Add("This is a string");
for (int i = 0; i < 1000000; i++)
ss = sa[i];
} public void testArrayListWithForEach()
{
ArrayList sa;
string ss;
sa = new ArrayList();
for (int i = 0; i < 10000000; i++)
sa.Add("This is a string");
foreach (string s in sa)
ss = s;
} public void testListWithForEach()
{
List<string> sa;
string ss;
sa = new List<string>();
for (int i = 0; i < 10000000; i++)
sa.Add("This is a string");
foreach (string s in sa)
ss = s;
} public void testListWithFor()
{
List<string> sa;
string ss;
sa = new List<string>();
for (int i = 0; i < 10000000; i++)
sa.Add("This is a string");
for (int i = 0; i < 10000000; i++)
ss = sa[i];
} public void testArrayWithFor()
{
string[] sa;
string ss;
sa = new string[10000000];
for (int i = 0; i < 10000000; i++)
sa[i] = "This is a string";
for (int i = 0; i < 10000000; i++)
ss = sa[i];
} public void testArrayWithForEach()
{
string[] sa;
string ss;
sa = new string[10000000];
for (int i = 0; i < 10000000; i++)
sa[i] = "This is a string";
foreach (string s in sa)
ss = s;
}
}
}

  然后是测试结果:

性能改善之For与Foreach-LMLPHP

所以当需要改善性能的时候,不仅需要用for,而且最好是用连续的存储空间类型的集合。

04-27 01:30