*** May 25th 2009: Revised post after important community feedback! Thanks.
By now it is a well known fact that it is not entirely trivial working with SPSite and SPWeb objects in the WSS object model when it comes to memory management. Forgetting to call the Dispose() method on objects you own, can result in a memory leak that might eventually bring down your SharePoint server. Fortunately, Microsoft has published a best practice to help SharePoint developers avoid this phenomenon. It basically says that you are r
esponsible for disposing all the SPSite and SPWeb objects you own.
However, I have by some reverse engineering learned that the SPSite object has a built-in safety value for disposing all SPWeb objects that were not disposed as prescribed by the best practice. But it only works if the parent SPSite object is disposed as prescribed. Consider the following example where we correctly dispose of all the objects we create.
using (SPSite site = new SPSite("http://server/sites/asite"))
{
using (SPWeb web = site.OpenWeb())
{
foreach (SPWeb subWeb in web.Webs)
{
// Perform operations...
subWeb.Dispose();
}
} // web.Dispose() automatically called.
} // site.Dispose() automatically called.
No memory leaks there - except if an exception is thrown just before subWeb.Dispose()! But a proper exception safe try/finally construct has been omitted not to clutter the example. Now, consider a scenario where someone forgot to dispose the SPWeb objects:
using (SPSite site = new SPSite("http://server/sites/asite"))
{
SPWeb web = site.OpenWeb(); // Oops! Forgot to wrap it in a using block
foreach (SPWeb subWeb in web.Webs)
{
// Perform operations...
// Oops! Forgot to call subWeb.Dispose()
}
} // site.Dispose() automatically called.
This is not a good coding practice but there is nevertheless no memory leak as the SPSite object tracks and disposes all SPWeb objects created through its factories. Now you know that the WSS object model will do its best to avoid any memory leaks in cases where developers accidentally forget disposing one or more SPWeb objects.
I can, however, not recommend taking advantage of this safety valve by deliberately omitting disposal of SPWeb objects. SharePoint developers should follow the best practice and dispose objects they create and at best as soon as they are done with them. Leveraging the SPDisposeCheck tool to identify potential leaks is also highly recommended.