Avoiding Unnecessary Construction of SPWeb and SPSite Objects
Applies to: SharePoint Foundation 2010
An SPWeb or SPSite object can occupy a lot of memory. Avoid constructing objects of these types simply to get a reference to a parent object. Instead, to get a reference to a web application, use the static SPWebApplication.Lookup(Uri) method, and pass it a Uri object that is created with the URI of the web application. You can then get a reference to the farm by using the Farm property of the web application object. (You can get a reference to a remote farm by using the static Open(String) method.) The ContentDatabases property of the web application object contains a collection of the content databases in the web application. You can get a reference to a particular content database through this property if you know its index in the collection. For more information, see the reference topic for the SPContentDatabaseCollection class. The following code illustrates some of these points.
SPWebApplication webApplication = SPWebApplication.Lookup(new Uri("https://localhost/");
SPFarm farm = webApplication.Farm;
SPContentDatabase content = webApplication.ContentDatabases[0];
Use the WebsInfo property whenever possible
One good way to avoid constructing SPWeb objects is to use the WebsInfo property whenever possible. That property contains information about each SPWeb object in a SPWebCollection.
Each WebsInfo object contains these properties for each SPWeb in a collection:
Configuration
CustomMasterUrl
Description
Id
Language
LastItemModifiedDate
MasterUrl
ServerRelativeUrl
Title
UIVersion
UIVersionConfigurationEnabled
WebTemplateId
This sample demonstrates how you can store these properties for each SPWeb object in a SPWebCollection without the expense of constructing any SPWeb objects
SPSite site = SPContext.Current.Site;
SPWebCollection subWebs = site.AllWebs;
foreach (SPWebInfo webInfo in subWebs.WebsInfo)
{
//Create a result object that contains information about each SPWeb in the collection.
var result = webInfo.Title +
webInfo.ServerRelativeUrl +
webInfo.Description +
webInfo.Id +
webInfo.Language +
webInfo.LastItemModifiedDate +
webInfo.WebTemplateId +
webInfo.Configuration +
webInfo.UIVersionConfigurationEnabled +
webInfo.UIVersion +
webInfo.MasterUrl +
webInfo.CustomMasterUrl;
}
If you’re curious to know just how much of a performance improvement you can get from using this property, this blog post on The SPWebCollection.WebsInfo property explains the results of some performance testing that demonstrates its efficiency.