Friday, January 29, 2010

Adding a new item to a SharePoint List

Using SPList.Items.Add() is not the best way to add a new item to a list. This is because the moment you access the get method on the Items collection it retrieves all the items into memory.

A quick peek at the Microsoft.SharePoint.dll assembly via reflector confirmed it:


You may not notice a difference in performance in the dev environment, but once your list starts to grow it will gradually degrade.

I recently learned this the hard way. This is the best way to add a new Item:

SPList list = _Web.Lists[LIST];                    SPQuery query = new SPQuery();
query.RowLimit = 0;
SPListItem item = list.GetItems(query).Add();
item[TITLE] = “testing”;

On an unrelated note, executing a query with a RowLimit generates an underlying SQL query such as  SELECT TOP X ..... where X is the RowLimit value.

I wonder if the behavior is still the same in SharePoint 2010. Hmmm...


More best practices on SharePoint:

No comments: