在C#.NET和VB.NET中迭代强类型泛型List的最佳方法是什么?
对于C#:
foreach(ObjectType objectItem in objectTypeList) { // ...do some stuff }
从Purple Ant回答VB.NET :
For Each objectItem as ObjectType in objectTypeList 'Do some stuff ' Next
对于IEnumerable的任何通用实现,最好的方法是:
//C# foreach( var item in listVariable) { //do stuff }
但是有一个重要的例外.IEnumerable涉及Current()和MoveNext()的开销,这是foreach循环实际编译成的内容.
当你有一个简单的结构数组:
//C# int[] valueTypeArray; for(int i=0; i < valueTypeArray.Length; ++i) { int item = valueTypeArray[i]; //do stuff }
更快.
更新
在与@Steven Sudit讨论之后(见评论)我认为我的原始建议可能已经过时或有误,所以我进行了一些测试:
// create a list to test with var theList = Enumerable.Range(0, 100000000).ToList(); // time foreach var sw = Stopwatch.StartNew(); foreach (var item in theList) { int inLoop = item; } Console.WriteLine("list foreach: " + sw.Elapsed.ToString()); sw.Reset(); sw.Start(); // time for int cnt = theList.Count; for (int i = 0; i < cnt; i++) { int inLoop = theList[i]; } Console.WriteLine("list for : " + sw.Elapsed.ToString()); // now run the same tests, but with an array var theArray = theList.ToArray(); sw.Reset(); sw.Start(); foreach (var item in theArray) { int inLoop = item; } Console.WriteLine("array foreach: " + sw.Elapsed.ToString()); sw.Reset(); sw.Start(); // time for cnt = theArray.Length; for (int i = 0; i < cnt; i++) { int inLoop = theArray[i]; } Console.WriteLine("array for : " + sw.Elapsed.ToString()); Console.ReadKey();
所以,我在发布中运行了所有优化:
list foreach: 00:00:00.5137506 list for : 00:00:00.2417709 array foreach: 00:00:00.1085653 array for : 00:00:00.0954890
然后调试没有优化:
list foreach: 00:00:01.1289015 list for : 00:00:00.9945345 array foreach: 00:00:00.6405422 array for : 00:00:00.4913245
所以它看起来相当一致,for
比foreach
数组更快,而且数组比通用列表更快.
然而,这是100,000,000次迭代,差异大约是最快和最慢方法之间的.4秒.除非你正在进行大规模的性能关键循环,否则不值得担心.