猿问

C#中“ for”和“ foreach”控制结构的性能差异

哪个代码段可以提供更好的性能?以下代码段是用C#编写的。


1。


for(int counter=0; counter<list.Count; counter++)

{

    list[counter].DoSomething();

}

2。


foreach(MyType current in list)

{

    current.DoSomething();

}


婷婷同学_
浏览 813回答 3
3回答

qq_遁去的一_1

一个for循环被编译的代码大约相当于这个:int tempCount = 0;while (tempCount < list.Count){&nbsp; &nbsp; if (list[tempCount].value == value)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // Do something&nbsp; &nbsp; }&nbsp; &nbsp; tempCount++;}其中,将foreach循环编译为大致等效于此的代码:using (IEnumerator<T> e = list.GetEnumerator()){&nbsp; &nbsp; while (e.MoveNext())&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; T o = (MyClass)e.Current;&nbsp; &nbsp; &nbsp; &nbsp; if (row.value == value)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Do something&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}正如您所看到的,这都取决于枚举器的实现方式以及列表索引器的实现方式。事实证明,基于数组的类型的枚举数通常是这样写的:private static IEnumerable<T> MyEnum(List<T> list){&nbsp; &nbsp; for (int i = 0; i < list.Count; i++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; yield return list[i];&nbsp; &nbsp; }}正如您所看到的,在这种情况下,它并没有太大的区别,但是链表的枚举数可能看起来像这样:private static IEnumerable<T> MyEnum(LinkedList<T> list){&nbsp; &nbsp; LinkedListNode<T> current = list.First;&nbsp; &nbsp; do&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; yield return current.Value;&nbsp; &nbsp; &nbsp; &nbsp; current = current.Next;&nbsp; &nbsp; }&nbsp; &nbsp; while (current != null);}在.NET中,您会发现LinkedList <T>类甚至没有索引器,因此您将无法在链表上进行for循环;但是如果可以的话,索引器的编写必须像这样:public T this[int index]{&nbsp; &nbsp; &nbsp; &nbsp;LinkedListNode<T> current = this.First;&nbsp; &nbsp; &nbsp; &nbsp;for (int i = 1; i <= index; i++)&nbsp; &nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; current = current.Next;&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp;return current.value;}如您所见,在循环中多次调用此方法要比使用可以记住它在列表中位置的枚举器慢得多。
随时随地看视频慕课网APP
我要回答