Summary: Common Coding Issues

Summary: Common Coding Issues

The Best Practice MSDN page has some interesting hints to generate better code. In this post I write about some point of that article, provide samples and fix bugs which are in the MSDN article.

Caching

You should only cache thread safe objects. What’s that?

This means, that you should only cache objects, which can not be changed from the outside of your code. An itemCollection (as list.Items) is changed, if another user adds an item. But if you cache a DataTable which you can get from an itemCollection with list.Items.GetDataTable() it will not be changed later on, and can be cached.

A lock should be put around reading the items and caching them. This will ensure that for the reading process, the items are not changed from the outside.

   1:  private static object _Lock = new object();
   2:   
   3:  public void CacheData(SPList list)
   4:  {
   5:      SPListItemCollection listItems;
   6:      lock (_Lock)
   7:      {
   8:          // Cache is your caching mechanism
   9:          DataTable dataTable = (DataTable) Cache["ListItemCacheName"];
  10:          if (dataTable == null)
  11:          {
  12:              listItems = list.GetItems(new SPQuery {RowLimit = 0});
  13:              dataTable = listItems.GetDataTable();
  14:              Cache.Add("ListItemCacheName", dataTable)
  15:          }
  16:      }
  17:  }

Event Receivers

Use the objects provided by the SPItemEventProperties parameter of your event method.

SPWeb web = properties.OpenWeb();

instead of

using (SPSite site = new SPSite(properties.WebUrl))
using (SPWeb web = site.OpenWeb())

Do not use SPList.Items

The Items property will return every list item. And it will read all items for every call to it. So every time your code has an .Items, a SQL query is generated, which reads all items. They have to be fetched, and stored in memory.

  • SPList.Items.Add()

Instead use SPList.AddItem we can not use SPList.AddItem, since it does not exist 🙁
So we query the list for 0 rows, and add a new list item to the itemCollection with 0 elements.

   1:  SPQuery query = new SPQuery {RowLimit = 0};
   2:  SPListItem newItem = list.GetItems(query).Add();
   3:  newItem[SPBuiltInFieldId.Title] = DateTime.Now.ToString();
   4:  newItem.Update();

Compared with list.Items.Add() the code runs significant faster. In my case I tested against a list with about 1100 items. A trace with the SQL Server Profiler showed, that the code took 19983 microseconds. Adding an item to SPList.Items took 288996 microseconds. This is 14 times more!

  • Get Items by Identifier

If you have an ID, get your list item through list.GetItemsByID(id). Otherwise use a SPQuery instead of iterating through all list items (see above).

  • Use paged Queries

The MSDN article provides some samples on how to get all list items. Not all at once, but 2000 at a time.

  • Use list.ItemCount instead of list.Items.Count
  • Use the PortalSiteMapProvider class (MOSS only!)

The PortalSiteMapProvider class uses caching by default. So if you need to query the same list, and it does not change frequently, you can increase the performance easily.

You can use the PortalSiteMapProvider for WSS sites, if you have MOSS installed. There is no need to activate MOSS features on the site, where you want to use the caching.

Also think about security trimming when you query for items, as you might only get a subset of all items in the initial load, if the user may not access all items!

   1:  SPWeb web = SPContext.Current.Web;
   2:  SPList list = web.Lists.Cast<SPList>().SingleOrDefault(
   3:      l => l.Title == "ListName");
   4:  if (list == null) return;
   5:   
   6:  PortalSiteMapProvider provider = PortalSiteMapProvider.WebSiteMapProvider;
   7:  PortalSiteMapNode webNode = 
   8:      (PortalSiteMapNode)provider.FindSiteMapNode(web.ServerRelativeUrl);
   9:  if (webNode == null || webNode.Type != NodeTypes.Area) return;
  10:   
  11:  Stopwatch watch = new Stopwatch();
  12:  watch.Start();
  13:  SPQuery query = new SPQuery { Query = list.DefaultView.Query };
  14:  SiteMapNodeCollection items = provider.GetCachedListItemsByQuery(
  15:      (PortalWebSiteMapNode)webNode, list.Title, query, web);
  16:   
  17:  foreach (PortalListItemSiteMapNode item in items)
  18:  {
  19:      string title = (string)item[SPBuiltInFieldId.Title];
  20:  }
  21:  watch.Stop();
  22:  Controls.Add(new LiteralControl(
  23:      "Items found: " + items.Count + " in " + watch.ElapsedMilliseconds + "ms"));

In the example, the stopwatch got about 2000 ms for the initial load. For each access to the items after they have been cached, it took 15-20 ms. So it is roughly 100 times faster!
You might have to adjust the query to your needs, since it uses the default view to get the items.

Conclusion

Review your code for memory leaks (SharePoint Diagnostics Tool (SPDiag)) and follow common coding issues to generate clean, safe and fast SharePoint code.

Leave a Reply