I came across this c# code in a project today and I couldn’t help but question its efficiency:
SPList spList = spWeb.GetListCustom("tasks");
foreach (SPListITem item in spList.GetItems(query))
{
//... do something with the SPListCollection it returned
}
Being from a Java background, the spList.GetItems(query) definitely made me think that its a performance hit. I would’ve done something like the following to improve it:
SPList spList = spWeb.GetListCustom("tasks");
SPListIteCollection taskListCollection = taskList.GetItems(query);
foreach (SPListITem item in taskListCollection)
{
//... do something with the SPListCollection it returned
}
However, the code is in C#…
So my question is: would the code I suggested above improve performance, or have I missed something fundamental about C#’s foreach loop?
Thanks.
The two blocks of code are completely identical, and will compile to the exact same IL in Release mode.
Unlike a regular
forloop, aforeachloop will only use the collection once (to callGetEnumerator). Therefore, you have nothing to worry about.