SPSite and SPWeb instantiation vs SPContext.SPSite and SPContext.SPWeb

Posted on Updated on

Most often that I wish I see really bad practices about this specific thing.
Most developers just open visual studio and the first thing they do is just

SPSite site= new SPSite(spcontext.current.site.url)

Others jut use SpContext.Current.Site.Url inmediately.

Well, I am going to explain some of reasons when you should use a new SPSite or SPWeb object or when you should use the SPContect.Current.Site and .Web.

The following list might grow as I start receiving comments via mail, but this is heavily explained in some other blogs out there:

1. The fact of doing a new SPSite or new SPWeb, it uses lots of SPRequest objects, creation of these 2 objects is highly resource intensive and very expensive in terms of CPU time.
2. No because you can, doesnt mean you should, This sentence is actually from Randy Williams, and with this permission I use it here, DO NOT start coding with a new object first, first think and then do.
3. SPContext should be used when you dont need to run some code with elevated privileges, SPContext uses the current user permissions, so be aware of that.
For example if you create an application page which reads a list, but that list is read only for all users, then you need RunWithElevatedPrivileges and then you need to instantiate the SPSite or SPWeb object.
4. When to instantiate a new SPSite or SPWeb.

  • When the running code is not inside a sharepoint context (eg: timer job, Client application)
  • When the running code needs to access resources that users normally wont have access to (eg: list data)
  • When you need to access data from another Site collection/site than the current

5. Another fact:

  • This is true in other areas of development, like SqlConnection.
  • Leave the objects opened only for the operations you need, the faster you close it the more resources you free.
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s