我編碼一個C#窗體應用程序,並想知道如果以下兩個功能實現同樣的結果:IEnumerable <T>函數的收益率比List <T>函數的效率更高嗎?
public List<object> Method1(int parentId)
{
List<object> allChildren = new List<object>();
foreach (var item in list.Where(c => c.parentHtmlNodeForeignKey == parentId))
{
allChildren.Add(item);
allChildren.AddRange(Method1(item.id));
}
return allChildren;
}
public IEnumerable<object> Method2(int parentId)
{
foreach (var item in list.Where(c => c.parentHtmlNodeForeignKey == parentId))
{
yield return item;
foreach (var itemy in Method2(item.id))
{
yield return itemy;
}
}
}
我是在說,Method1
功能比Method2
更有效的糾正?
此外,上述任何一種功能都可以編碼爲更高效?
編輯
我使用的函數返回某些對象,然後在ListView顯示。然後我循環這些相同的對象來檢查是否有字符串出現。
謝謝。
難以閱讀所有這些長名。 'Method1','Method2'有什麼問題? –
他們如何被使用?你是否多次迭代resluts?你是否遍歷所有結果? –
這取決於你如何使用該功能。 Yield函數按需執行,因此對函數的單個調用所需的運行時間少於List函數(但不會得到結果)。 Yield函數需要構建迭代器對象的開銷。所以如果你對Yield方法的結果調用'ToList()',這可能比純粹的'List'函數慢。 –