What is the difference between SPContext.Current.Web.Site.OpenWeb (). Lists ["List"]; and SPContext.Current.Web.Lists ["List"]?

I need to reorganize some sharepoint 2010 code from my college. Each time he needs to access the list, he does this:

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

I used this:

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

What is the difference between the two and the more effective?

+4
source share
4 answers

The second method is much more efficient.

In the first method, you create a new SPWeb object through an OpenWeb() call, which is an expensive call. Note that you must also explicitly deny this object manually when you are done with it.

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

+4
source

Agree with Madhur

Use 2nd approach as it will not perform memory leak

By the way: In SP2010 there is a new method for getting SPList

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

use

+1
source

Another point in performance is that the operator SPContext.Current.Web.Site.OpenWeb().Lists["List"] will access the List from the current site SPContext.Current.Web.Lists["List"]; , and the line SPContext.Current.Web.Lists["List"]; will get access to the list from the current network, but not from the current site collection.


Consider this scenario ...

Consider whether the Employee list exists in the site http://[web-app]/sites/sa .

And the sa site database has a child node.

Then, if you use this line SPContext.Current.Web.Lists["List"]; , then she will try to find the list on the network inside sa / en-us, which, in turn, throws an error.

While using the instruction SPContext.Current.Web.Site.OpenWeb().Lists["List"]; a list will be found in the site collection and successfully launched.

+1
source
Madhur is right about the expensive code. At first I thought that he was mistaken in directly disposing of him, but he is also right. According to Best Practices documentation:

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

However, you use the OpenWeb () method for the SPContext object, which returns a new SPWeb object if you look at the decompiled assembly. Therefore, it must be explicitly indicated.

0
source

Source: https://habr.com/ru/post/1390009/


All Articles