I have to refactor some sharepoint 2010 code from my collegue. Everytime he needs to access a list he does this:

SPContext.Current.Web.Site.OpenWeb().Lists["List"];

I used to do this:

SPContext.Current.Web.Lists["List"];

What's the difference between these two and whats the more efficient way?

4

There are 4 answers

0
Madhur Ahuja On BEST ANSWER

The second is much more efficient way.

In the first method, you are creating a new SPWeb object through the OpenWeb() call which is an expensive call. Note only that, you must also explicitly dispose this object manually when you are done using that.

Read here: http://msdn.microsoft.com/en-us/library/aa973248(v=office.12).aspx

0
Sandeep On

Agree with Madhur

Use the 2st approach as it will not do any memory leakage

By the way : In SP2010 there is a new method to get SPList

SPContext.Current.Web.Lists.TryGetList("ListName");

use that

0
sharepointbee On

Another point in-lieu of performance is that the statement SPContext.Current.Web.Site.OpenWeb().Lists["List"] will access the list List from the current site collection while the line SPContext.Current.Web.Lists["List"]; will access the list from the current web, but not from the current site collection.


Consider this scenario...

Consider there is a list Employee exists at the site collection http://[web-app]/sites/sa.

And there is subsite en-us at sa site collection.

Then if use this line SPContext.Current.Web.Lists["List"]; then it will try to find the list in the web inside the sa/en-us which in turn throw a error.

Whilw using the statement SPContext.Current.Web.Site.OpenWeb().Lists["List"]; will find the list in sa site collection and run successfully.

0
Levent On

Madhur is right about the expensive code. I first thought that he was wrong about disposing it explicitly, but he is right on that as well. According to the Best Practices documentation:

SPContext objects are managed by the SharePoint framework and should not be explicitly disposed in your code. This is true also for the SPSite and SPWeb objects returned by SPContext.Site, SPContext.Current.Site, SPContext.Web, and SPContext.Current.Web.

However you are using OpenWeb() method on a SPContext object which returns a new SPWeb object if you look at the decompiled assembly. Hence, it needs to be disposed explicitly.