There's far too much of this type of code floating around*:
SPList list = web.Lists["Web Part Gallery"];
// go through the items in reverse
for (int i = list.ItemCount - 1; i >= 0; i--)
{
string name = list.Items[i].Name;
if (name == someCondition)
{
list.Items[i].SomeAction();
}
}
*copied from here: http://cks.codeplex.com/SourceControl/changeset/view/26423#358362
** this particular code also incorrectly disposes the Feature's site and web, but that's another story
Looks innocuous enough, but look at the internals of the SPList.Items property:
public virtual SPListItemCollection Items
{
get
{
SPQuery query = new SPQuery();
query.ViewAttributes = "Scope=\"Recursive\"";
return this.GetItems(query);
}
}
This means the code above runs a recursive query accross all list items every time the indexer is accessed, so in the code above if there are, say 10 webparts, the webpart list is queried 20 times.
The better way to do this is to create a local SPListItemCollection instance and use it in the loop, the query is now run only once:
SPListItemCollection webParts = web.Lists["Web Part Gallery"].Items;
// go through the items in reverse
for (int i = webParts.Count - 1; i >= 0; i--)
{
string webpartName = webParts[i].Name;
if (webpartName == someCondition)
{
webParts[i].SomeAction();
}
}
Also see http://mo.notono.us/2009/03/beware-of-splistitemsadd.html for a warning regarding SPList.Items.Add()