亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

C#中“ for”和“ foreach”控制結構的性能差異

C#中“ for”和“ foreach”控制結構的性能差異

婷婷同學_ 2019-10-28 14:47:49
哪個代碼段可以提供更好的性能?以下代碼段是用C#編寫的。1。for(int counter=0; counter<list.Count; counter++){    list[counter].DoSomething();}2。foreach(MyType current in list){    current.DoSomething();}
查看完整描述

3 回答

?
qq_遁去的一_1

TA貢獻1725條經驗 獲得超8個贊

一個for循環被編譯的代碼大約相當于這個:


int tempCount = 0;

while (tempCount < list.Count)

{

    if (list[tempCount].value == value)

    {

        // Do something

    }

    tempCount++;

}

其中,將foreach循環編譯為大致等效于此的代碼:


using (IEnumerator<T> e = list.GetEnumerator())

{

    while (e.MoveNext())

    {

        T o = (MyClass)e.Current;

        if (row.value == value)

        {

            // Do something

        }

    }

}

正如您所看到的,這都取決于枚舉器的實現方式以及列表索引器的實現方式。事實證明,基于數組的類型的枚舉數通常是這樣寫的:


private static IEnumerable<T> MyEnum(List<T> list)

{

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

    {

        yield return list[i];

    }

}

正如您所看到的,在這種情況下,它并沒有太大的區別,但是鏈表的枚舉數可能看起來像這樣:


private static IEnumerable<T> MyEnum(LinkedList<T> list)

{

    LinkedListNode<T> current = list.First;

    do

    {

        yield return current.Value;

        current = current.Next;

    }

    while (current != null);

}

在.NET中,您會發現LinkedList <T>類甚至沒有索引器,因此您將無法在鏈表上進行for循環;但是如果可以的話,索引器的編寫必須像這樣:


public T this[int index]

{

       LinkedListNode<T> current = this.First;

       for (int i = 1; i <= index; i++)

       {

            current = current.Next;

       }

       return current.value;

}

如您所見,在循環中多次調用此方法要比使用可以記住它在列表中位置的枚舉器慢得多。


查看完整回答
反對 回復 2019-10-28
  • 3 回答
  • 0 關注
  • 836 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號