Sharepoint - Iterating through SPListItemCollection - why foreach is bad?
Generally speaking you will want to use SPQuery to only query items you're interested in.
Unless you're doing
SPList oList = web.GetList("XYZ");
for(int i=0; i < oList.Items.Count; i++)
{
string strLstItemName = oList.Items[i].Name; // << BAD, as you use Items here, so you fetch them from DB each loop
}
there shouldn't be any relevant difference between your bad and good examples. It's not like foreach would fetch the whole Items collection from DB on each loop.
See Kobi's answer here. Also, I don't think generic .NET performance aspects play much of a role here as DB roundtrip is any way the slowest. Of course, with HUGE list you may end up waiting 60 secs for the data to arrive from DB to SharePoint, and THEN you can save 1 sec in using for loop instead of foreach.
As long as you stick to the principle of storing the SPListItemCollection
in a variable before looping through the items, the difference between using for
instead of foreach
is close to redundant.
The foreach
loop will be converted into a for
loop under the hood. It's a 1, perhaps 2 sec, difference.
So if you write:
var listItems = SPContext.Current.List.Items;
foreach (SPListItem item in listItems)
{
Console.Write(item.Title);
}
Instead of:
var listItems = SPContext.Current.List.Items;
for (var i = 0; i < listItems.Count; i++)
{
var item = listItems[i];
Console.Write(item.Title);
}
Doesn't really make a difference.
In the context of general c# comparistions between for
and foreach
- There is a pretty comphrensive discussion here
for
loops on List are a bit more than 2 times cheaper thanforeach
loops on List.- Looping on array is around 2 times cheaper than looping on List.
- As a consequence, looping on array using
for
is 5 times cheaper than looping on List using foreach (which I believe, is what we all do).
The source quoted in the above discussion - here