第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

C#中“ for”和“ foreach”控制結(jié)構(gòu)的性能差異

C#中“ for”和“ foreach”控制結(jié)構(gòu)的性能差異

婷婷同學(xué)_ 2019-10-28 14:47:49
哪個(gè)代碼段可以提供更好的性能?以下代碼段是用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貢獻(xiàn)1725條經(jīng)驗(yàn) 獲得超8個(gè)贊

一個(gè)for循環(huán)被編譯的代碼大約相當(dāng)于這個(gè):


int tempCount = 0;

while (tempCount < list.Count)

{

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

    {

        // Do something

    }

    tempCount++;

}

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


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

{

    while (e.MoveNext())

    {

        T o = (MyClass)e.Current;

        if (row.value == value)

        {

            // Do something

        }

    }

}

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


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

{

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

    {

        yield return list[i];

    }

}

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


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中,您會(huì)發(fā)現(xiàn)LinkedList <T>類甚至沒有索引器,因此您將無法在鏈表上進(jìn)行for循環(huán);但是如果可以的話,索引器的編寫必須像這樣:


public T this[int index]

{

       LinkedListNode<T> current = this.First;

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

       {

            current = current.Next;

       }

       return current.value;

}

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


查看完整回答
反對 回復(fù) 2019-10-28
  • 3 回答
  • 0 關(guān)注
  • 835 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號