Partager via


Optimizing Code Performance

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 in setting properties or calling the method for updating. This is not a recommended practice.

Example: (Not Recommended)

[Visual Basic .NET]

Dim myWeb As SPWeb = SPControl.GetContextWeb(Context)

myWeb.Lists("Tasks").Title = "List_Title"
myWeb.Lists("Tasks").Description = "List_Description"
myWeb.Lists("Tasks").Update()

[C#]

SPWeb myWeb = SPControl.GetContextWeb(Context);

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)

[Visual Basic .NET]

Dim myWeb As SPWeb = SPControl.GetContextWeb(Context)

Dim myList As SPList = myWeb.Lists("Tasks")

myList.Title="List_Title"
myList.Description="List_Description"
myList.Update()

[C#]

SPWeb myWeb = SPControl.GetContextWeb(Context);

SPList myList = myWeb.Lists["Tasks"];

myList.Title="List_Title";
myList.Description="List_Description";
myList.Update();

The object models in the Windows SharePoint Services 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.