How to Write SharePoint Code for Bad Performance

Whilst browsing some SharePoint blogs I came across an interesting code sample. The code showed how to edit item properties in an Event Receiver on a library.Here's a partial excerpt;

using (SPSite site = new SPSite(properties.Web.Site.ID))

{

    using (SPWeb web = site.OpenWeb(properties.Web.ID))

    {

        SPList list = web.Lists[properties.List.ID];

 

        SPListItem item = list.Items.GetItemById(properties.ListItemId);

 

 This code caught my eye, because it was totally unnecessary to instantiate the SPSite and SPWeb objects to get a handle to the list item. Far better to just use event properties without instantiating anything!

properties.ListItem

 So, in for a penny, in for a pound I thought I'd compare the code performance. In a standalone dev environment with a few list items the bad code would run fine. I have access to a test environment with tens of thousands of items, which provided a better test of Production-like conditions.

The good code executed in 30ms fairly consistently, according to the logs. Fair enough. 

What I found was the bad code execution time started climbing as I fired more and more items into the list and triggered the event receiver more often. I gave up when the bad code was executing in 12000 milliseconds.

Yup. In my sizable library, the bad code ran 400 times slower than the code using properties.ListItem!!

This is why it's not good practice instantiating unnecessary SPSite and SPWeb objects. (So also consider SPContext.Current when you're not in Event Receivers for similar reasons).

Also shows you why you shouldn't trust code samples on blogs without a bit of code review (including mine!).

Happy SharePointing!