Memory Leak in SharePoint Code?

438 views Asked by At

I am just wondering how to find out a memory leak in a code. I am working on a code written by someone else and been told that it has a memory leak. I am going through the code to see if it has a memory leak.

does following code has memory leak. do i need to close the SPWEB objects here.

     private bool isSubSite()
    {

        SPWeb currWeb = SPContext.Current.Web;
        SPWeb rootWeb = currWeb.Site.RootWeb;

        if (currWeb.ID != rootWeb.ID)
            return true;
        return false;
    }
3

There are 3 answers

3
andre_ss6 On BEST ANSWER

Edit: Sorry, I've just noticed you're getting SpContext.Current.Web. That is a shared resource, and thus you should not call dispose on it, as pointed out by @Servy. Let the framework take care of that for you.


You need to dispose of the SPWeb objects. You can either call Dispose yourself after you no longer need them, or you can use the using statement, which automatically disposes the object for you:

  private bool isSubSite()
{

    using (SpWeb currWeb = SpContext.Current.Web){
        using (SPWeb rootWeb = currWeb.Site.RootWeb){

            if (currWeb.ID != rootWeb.ID)
                return true;
            return false;
        }
    }
}

Note that there is no problem returning inside the using, as this code will be translated into a try...finally code block later with the call to dispose inside the finally block, thus making sure it will be executed regardless of function returning or exceptions thrown.

Also, note that you should not call neither Dispose or Close on shared SpWeb objects. As this is not the case, you can call them safely.

0
Servy On

No, that code does not have a memory leak.

No, you should not be disposing of those SPWeb objects. If you do dispose of them then when those SPWeb objects are used on subsequent requests, or in subsequent locations of the current request, it will fail. The framework code created the SPWeb object and assigned it to the current context is responsible for disposing of it.

1
ErstwhileIII On

Simplify the code to:

private bool isSubSite()
    { return SPContext.Current.Web.ID != currWeb.Site.RootWeb.ID;}

No way from looking at your code to determine whether it could be a source of a memory leak (but the code above only uses temporary references).