Reputation: 341
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;
}
Upvotes: 4
Views: 474
Reputation: 4853
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).
Upvotes: -2
Reputation: 1254
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.
Upvotes: 1
Reputation: 203844
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.
Upvotes: 5