Lars Nielsen's Discoveries

June 15, 2010

Performance code tips for SharePoint

Filed under: Development,Good Practice,SharePoint — Lars Nielsen @ 7:02 pm
Tags: ,

I thought I’d collect together some tips on how to improve the performance of code in SharePoint and how to avoid some traps which might cause code to run slowly or break in production systems.

1) Accessing Lists

You need to be careful when working with SharePoint lists – often code that might work fine on a dev machine with small lists won’t work so well when you deploy it to a production environment where the lists are much bigger.  In particular, watch out for the right way and wrong way to loop through the items in a list.  Never loop through the SPList.Items object, because SharePoint will query the database each time within the loop.  Instead set a new SPListItemCollection variable to point to SPList.Items and then loop through the new variable.   This will cut it down to just one query to get all the items in one go, rather than one at a time.

Even better is to the GetList() method of the SPWeb to get a reference to the list.  This is less demanding in terms of database access and also you can test if the list is there by trapping a FileNotFoundException which is thrown by the method if the list does not exist.  Use code like this to get a reference to the list:


string listName = "My List"

try
{
string s = _currentSPContext.Site.ServerRelativeUrl; // Site collection root Url
if (!string.IsNullOrEmpty(s))
{
          string siteCollectionRelativeUrl = s.TrimEnd('/');
SPList MyList = _currentSPContext.Site.RootWeb.GetList(siteCollectionRelativeUrl + "/Lists/" + listName);
.....
}
}

catch (FileNotFoundException)
{
    .....
}

2) Counting items in a list

In the same way, it’s better to use SPList.ItemCount rather than SPList.Items.Count, again to prevent multiple queries on the database.  Although the results do differ if you have folders in the list – SPList.ItemCount counts a folder as one item, whereas SPList.Items.Count ignores the folders.

Here are a load more great best practice advice

[Update: 28/3/2012]

I just found this great post with lots of detail and advice on good and bad ways to work with lists in the object model.  It’s quite old now but I think it’s still valid for SharePoint 2010

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: