Optimizing Code Performance
Applies to: SharePoint Foundation 2010
Avoid creating and destroying objects unnecessarily in code, as this may require that extra queries be made against the database and may even involve code that is incorrect.
In the following example, separate objects for the Tasks list must be instantiated each time the indexer is used to set properties and the method for updating is called. This is not a recommended practice.
Example: (Not Recommended)
Dim myWeb As SPWeb = SPContext.Current.Web
myWeb.Lists("Tasks").Title = "List_Title"
myWeb.Lists("Tasks").Description = "List_Description"
myWeb.Lists("Tasks").Update()
SPWeb myWeb = SPContext.Current.Web;
myWeb.Lists["Tasks"].Title = "List_Title";
myWeb.Lists["Tasks"].Description = "List_Description";
myWeb.Lists["Tasks"].Update();
The following example instantiates the Tasks list object only once and assigns it to the myList variable in order to set properties and call the method.
Example: (Recommended)
Dim myWeb As SPWeb = SPContext.Current.Web
Dim myList As SPList = myWeb.Lists("Tasks")
myList.Title="List_Title"
myList.Description="List_Description"
myList.Update()
SPWeb myWeb = SPContext.Current.Web;
SPList myList = myWeb.Lists["Tasks"];
myList.Title="List_Title";
myList.Description="List_Description";
myList.Update();
The previous example requires a using directive (Imports in Visual Basic) for the Microsoft.SharePoint namespace.
The object models in the Microsoft.SharePoint assembly optimize performance and minimize the number of SQL queries that are made. However, to monitor code performance, it is recommended that you use the SQL Profiler.
To return a single item from a collection, always use a Get* method when one is provided through a parent object, instead of iterating through the entire collection and using an indexer. For example, the SPWeb class provides GetFile, GetFolder, and GetListItem methods that you can use to return single items.