Saturday, February 21, 2009

How to get SPList instance

Usually the developers write code like this:

using (SPSite siteCollection = new SPSite(siteUrl))
{
    using (SPWeb web = siteCollection.OpenWeb())
    {
        SPList myList = web.Lists["ListTitle"];
    }
}

It seems good, consistent with best practices http://msdn.microsoft.com/en-us/library/aa973248.aspx#sharepointobjmodel__codingtechniques, but whether it is really the best?

In this case web.Lists["ListTitle"]; loads metadata for all lists in this SPWeb and than compares the titles (SPList.Title) of all objects in the collection. Finally it returns the list matching the criteria.

Let’s see the code below.

using (SPSite siteCollection = new SPSite(siteUrl))
{
    using (SPWeb web = siteCollection.OpenWeb())
    {
        SPList myList = web.GetList(“http://site_url/lists/ListTitle/AllItems.aspx”);
    }
}

In this case the Object Model at first gets the List ID (GUID) from the URL, than loads the metadata only for this specific list.

Yes, that is not a big performance problem if you have a few lists in your SPWeb. But let’s consider what will happen if there are 1000 lists per site…?

3 comments:

  1. It’s always good to use new good practice!!!
    Thanks

    ReplyDelete
  2. Hi there

    I did some research on the internals of the SharePoint Object Model and uncovered some of the things that go on under-the-hood. There are some interesting things that you should consider when developing againt the SharePoint API.
    check out my blog series @ http://blog.dynatrace.com/tag/sharepoint-net/

    ReplyDelete