Saturday, January 21, 2012

We are learning so many concepts each day and implementing/writing lot of code. But, we might not spending time to write the code more efficient way or more cleaner way. So, this post is again related to how to write code efficient in SharePoint 2010. :)

So far, till SharePoint 2007 to loop through all the webs in site collection we use the code:
using(SPSite site = new SPSite("http://sitecollectionurl")
{
foreach(SPWeb web in site.AllWebs)
{
//Some code here
web.Dispose();
}
}
The above code is not at all wrong.

Case 1:
If you need the web object only for reading the generic information of the site like title, url, id etc… then it is a very expensive operation. For this, in SharePoint 2010 there is a workaround and that will load results 10 times faster than above code. Below is the efficient code:
using(SPSite site = new SPSite("http://sitecollectionurl")
{
foreach(SPWebInfo webInfo in site.AllWebs.WebsInfo)
{
//Code here to read web information 
}
}
This way you only reading the web information object instead of complete Web object. You can take a look more about WebInfo class here in MSDN.

Case 2:
If you want to read the properties you needed then there is a more better way than simply loop through AllWebs property in for each. The complete explaination is here. This is a very good post and very very faster way to read the properties in all webs.

You really see the difference, a big difference. Do you like this post?

Categories:

1 comment:

  1. This is a great way to increase site load times and will definitely improve organizational performance during peak hours. Great find. i can only imagine what type of impact this has on customer facing SharePoint sites.

    ReplyDelete