I’ve read several blog posts of late regarding best practices for developing SharePoint API based components. Some developers are aware of issues surrounding disposal of SPSite and SPWeb objects and the use of SPList Item collections, and some are not. The simple fact is the SharePoint API is not intuitive when it comes usage of memory hungry-object instances, and it is all too easy to leave too many of these objects in memory for the garbage collector to deal with – causing large memory spikes in the site application pool with high traffic utilization. Furthermore, what seems like innocent well structured code can perform badly because of the underlying calls against the SharePoint content databases. This blog post serves as a reference point and as a quick summary of some of the best practices.
Best Practices: Using Disposable Windows SharePoint Services Objects
Enable the following registry setting to populate the ULS logs with allocation identifiers to isolate non-disposed SPSite and SPWeb objects:
HKEY_LOCAL_MACHINESOFTWAREMicrosoftShared ToolsWeb Server ExtensionsHeapSettings SPRequestStackTrace = 1
Wrap all calls that create a new SPSite or SPWeb object (except those from obtained from the SPContext.Current singleton) in try, catch, finally blocks, or using statements
SPContext objects are managed by the SharePoint framework and should not be explicitly disposed in your code. This is true also for the SPSite and SPWeb objects returned by SPContext.Site, SPContext.Current.Site, SPContext.Web, and SPContext.Current.Web.
You must be cautious and aware of what the runtime is doing whenever you combine SharePoint object model calls on the same line. Leaks arising from this scenario are among the hardest to find.
The finally block executes after calls to Response.Redirect in the try block. Response.Redirect ultimately generates a ThreadAbortException. When this exception is raised, the runtime executes all finally blocks before ending the thread. However, because the finally block can do an unbounded computation or cancel the ThreadAbortException, there is no guarantee that the thread will end. Therefore, before any redirection or transfer of processing can occur, you must dispose of the objects. If your code must redirect, implement it in a way similar to the following code example.
SPSite oSPSite = null;
SPWeb oSPWeb = null;
oSPSite = new SPSite("http://server");
oSPWeb = oSPSite.OpenWeb(..);
str = oSPWeb.Title;
if (oSPWeb != null)
if (oSPSite != null)
if (oSPWeb != null)
if (oSPSite != null)
Good practices to reduce object long-term retention:
- If you create the object with a new operator, ensure that the creating application disposes of it.
- Dispose of items created by SharePoint methods that return other SPWeb objects (such as OpenWeb).
- Do not share any SPRequest object (and by extension any object that contains a reference to an SPRequest object) across threads.
- The SPSiteCollection.Add method creates and returns a new SPSite object. You should dispose of any SPSite object returned from the SPSiteCollection.Add method.
- The SPSiteCollection  index operator returns a new SPSite object for each access. An SPSite instance is created even if that object was already accessed. The following code samples demonstrate improper disposal of the SPSite object.
- The SPSite.AllWebs.Add method creates and returns an SPWeb object. You should dispose of any SPWeb object returned from SPSite.AllWebs.Add.
- The SPWebCollection.Add method creates and returns an SPWeb object that needs to be disposed.
- The SPSite.AllWebs  index operator returns a new SPWeb instance each time it is accessed.
- The OpenWeb method and SelfServiceCreateSite method (all signatures) create an SPWeb object and return it to the caller.
- The Microsoft.Office.Server.UserProfiles.PersonalSite returns an SPSite object that must be disposed.
An earlier version of this article indicated that the calling application should dispose of the SPSite.RootWeb property just before disposing of the SPSite object that is using it. This is no longer the official guidance. The dispose cleanup is handled automatically by the SharePoint framework. Additionally, SPSite properties LockIssue, Owner, and SecondaryContact used the RootWeb property internally. Given the updated guidance for RootWeb, it is no longer advisable to call the Dispose method on the SPSite.RootWeb property whenever any of these properties are used.
- The SPWeb.Webs property returns an SPWebCollection object. The SPWeb objects in this collection must be disposed.
- The SPWeb.Webs.Add method (or Add) creates and returns a new SPWeb object. You should dispose of any SPWeb object returned from this method call.
- The SPWeb.Webs index operator returns a new SPWeb object for each access
An earlier version of this article recommended that the calling application should dispose of the SPWeb.ParentWeb. This is no longer the official guidance. The dispose cleanup is handled automatically by the SharePoint framework.
- Microsoft.SharePoint.Portal.SiteData.Area.Web Property. The Web property returns a new SPWeb object each time it is accessed.
- If the object is obtained from the SharePoint context objects (GetContextSite method and GetContextWeb method), the calling application should not call the Dispose method on the object.
- The SPLimitedWebPartManager class contains a reference to an internal SPWeb object that must be disposed.
- The GetPublishingWebs method of the PublishingWeb class returns a PublishingWebCollection object. You must call the Close method on each enumerated innerPubWeb object. When you are calling only the GetPublishingWeb method, you are not required to call Close.
- The Microsoft.SharePoint.Publishing.PublishingWeb.GetVariation method returns a PublishingWeb object that must be disposed.
Best Practices: Common Coding Issues When Using the SharePoint Object Model
Caching Data and Objects
Many developers use the Microsoft .NET Framework caching objects (for example, System.Web.Caching.Cache) to help take better advantage of memory and increase overall system performance. But many objects are not "thread safe" and caching those objects can cause applications to fail and unexpected or unrelated user errors.
Caching SharePoint Objects That Are Not Thread Safe
You might try to increase performance and memory usage by caching SPListItemCollection objects that are returned from queries. In general, this is a good practice; however, the SPListItemCollection object contains an embedded SPWeb object that is not thread safe and should not be cached.
You can cache a DataTable object that is created from the SPListItemCollection object.
Using Objects in Event Receivers
Do not instantiate SPWeb, SPSite, SPList, or SPListItem objects within an event receiver. Event receivers that instantiate SPSite, SPWeb, SPList, or SPListItem objects instead of using the instances passed via the event properties can cause the following problems:
- They incur significant additional roundtrips to the database. (One write operation can result in up to five additional roundtrips in each event receiver.)
- Calling the Update method on these instances can cause subsequent Update calls in other registered event receivers to fail.
Working with Folders and Lists
Do not use SPList.Items. SPList.Items selects all items from all subfolders, including all fields in the list.
- Instead of calling SPList.Items.Add, simply use SPList.AddItem.
- Retrieve list items using SPList.GetItems(SPQuery query)
- Instead of using SPList.Items.GetItemById, use SPList.GetItemById(int id, string field1, params string fields)
Do not enumerate entire SPList.Items collections or SPFolder.Files collections.
|Poor Performing Methods and Properties||Better Performing Alternatives|
|SPList.Items.XmlDataSchema||Create an SPQuery object to retrieve items you want|
|SPList.Items.NumberOfFields||Create an SPQuery object (specifying the ViewFields)|
|SPList.Items.ReorderItems||Perform a non-paged query using SPQuery in each page|
Use PortalSiteMapProvider (Microsoft Office SharePoint Server 2007 only).
Steve Peschka's white paper Working with Large Lists in Office SharePoint Server 2007 describes an efficient approach to retrieving list data in Office SharePoint Server 2007 by using the PortalSiteMapProvider class.
(Very important as this works around the 2000 item limit)
How to make this code more scalable or fine-tune it for a multiple user environment can be a hard question to answer. It depends on what the application is designed to do.
You should take the following into consideration when asking how to make code more scalable:
Is the data static (seldom changes), somewhat static (changes occasionally), or dynamic (changes constantly)?
Is the data the same for all users, or does it change? For example, does it change depending on the user who is logged on, the part of the site being accessed, or the time of year (seasonal information)?
Is the data easily accessible or does it require a long time to return the data? For example, is it returning from a long-running database query or from remote databases that can have some network latency in the data transfers?
Is the data public or does it require a higher level of security?
What is the size of the data?
Is the SharePoint site on a single server or on a server farm?
Using SPQuery Objects
SPQuery objects can cause performance problems whenever they return large result sets. The following suggestions will help you optimize your code so that performance will not suffer greatly whenever your searches return large numbers of items.
- Do not use an unbounded SPQuery object.
- An SPQuery object without a value for RowLimit will perform poorly and fail on large lists. Specify a RowLimit between 1 and 2000 and, if necessary, page through the list.
- Use indexed fields.
- If you query on a field that is not indexed, the query will be blocked whenever it would result in a scan of more items than the query threshold (as soon as there are more items in the list than are specified in the query threshold). Set SPQuery.RowLimit to a value that is less than the query threshold.
- If you know the URL of your list item and want to query by FileRef, use SPWeb.GetListItem(string strUrl, string field1, params string fields) instead.