将查询放入C#foreach条件的效率

Ber*_*Cim 4 .net c# performance

我今天在一个项目中遇到了这个c#代码,我不禁质疑它的效率:

SPList spList = spWeb.GetListCustom("tasks");
foreach (SPListITem item in spList.GetItems(query))
{
    //... do something with the SPListCollection it returned
}
Run Code Online (Sandbox Code Playgroud)

来自Java背景,spList.GetItems(查询)肯定让我认为它的性能受到了打击.我会做类似以下的事情来改进它:

SPList spList = spWeb.GetListCustom("tasks");
SPListIteCollection taskListCollection = taskList.GetItems(query);
foreach (SPListITem item in taskListCollection)
{
    //... do something with the SPListCollection it returned
}
Run Code Online (Sandbox Code Playgroud)

但是,代码是在C#中...

所以我的问题是:我上面建议的代码会提高性能,还是我错过了关于C#的foreach循环的基本内容?

谢谢.

SLa*_*aks 14

这两个代码块完全相同,并将在Release模式下编译为完全相同的IL.

与常规for循环不同,foreach循环只使用集合一次(调用GetEnumerator).因此,您无需担心.