1

I want to know that what effects will cause if I open SPSite and SPWeb objects more than once in a code file (c#)

I have a implementation like below, can anyone tell me that what effects will it cause on my overall site performance ?

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        if (!IsPostBack)
        {
               var subjectList = GetSubjectData();
                HdnAllSubjects.Value = new JavaScriptSerializer().Serialize(subjectList);
                GenerateGrid();
                FillGrid(0, string.Empty); 

            else
            {

            }
        }
    }
    catch (Exception ex)
    {
        LogException.Log(ex);
        throw ex;
    }
} 

 private List<IdValuePair> GetSubjectData()
{
    using (SPSite site = new SPSite(SPContext.Current.Web.Url))
        {
            using (SPWeb web = site.OpenWeb())
            {
            }
        }
}

 private void GenerateGrid()
    {
        // some lines of codes here 
    }

public void FillGrid(int currentPageNumber, string pagingInfo)
{
    try
    {
        // Dstring subjectString = string.Empty;
        using (SPSite ospsite = new SPSite(SPContext.Current.Web.Url))
        {
            using (SPWeb ospweb = ospsite.OpenWeb())
            {
            }
        }
    }
}

Thannks

1

The rule is simple: open as many SPSite/SPWeb as you can. opening these SharePoint objects has a high cost (the highest in all SP Object Model): these are the objects that hold the connections to the DB. And each time you open them, a "huge" amount of data goes between the DB and the front-end, and is then loaded into memory on the front-end.

In addition, there's no point in opening these objects in your code: you're only re-opening the contextual objects (SPContext.Current.Web). No elevation, and not another site collection: you're wasting resources for nothing at all. SPContext.Current.Web exists for such situations: an object is being opened by SharePoint at the begin of the page lifecycle, and will automatically dispoed at the end; meanwhile, every component that wants access to it can do it with no cost at all.

  • thanks for answer. I have a query that i was asked during interview. why we need to dispose SPWeb and SPSite objects only why not SPList and others objects...? – Ankur Feb 20 '16 at 9:05
  • 1
    SPSite and SPWeb objects are the ones that hold an SPRequest instance. SPRequest is responsible for all DB connections and requests: so, even if you want to retrieve properties of a list or get list items, it goes through that SPRequest. Also, the SPRequest is a wrapper around COM objects (a legacy from SP2001): that's why it needs explicit disposal: to release the COM objects. – Evariste Feb 20 '16 at 14:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.