When you begin with Sharepoint like it did (and still do), you will ask your self: “What object should I dispose ?”. It’s quite important because Sharepoint leaks approximately 1 Mb per “IDisposable object not disposed”. If it’s a menu, it could quickly make you loose 10 Mb per loaded page.

The best and complete answer is in the MSDN. But it’s a pretty long answer.

The short answer is :

In your webpart, you should dispose every SPWeb and SPSite you use except:

  • SPContect.Current.Site
  • SPContext.Current.Web
  • SPContext.Current.Site.RootWeb

In your features, you should dispose every SPWeb and SPSite you use except the ones given in your “properties” variable.

The reason is that Sharepoint gives these objects to every component it will launch, if you dispose one of these objects, the next component loaded by sharepoint has a good chance to crash. And it’s not always easy to debug as it’s the NEXT component which will crash also it’s the previous one that messed up one of the sharepoint context variables.

If your not sure that you will Dispose an object you should, you shoud check. The following code Disposes the SPWeb passed as argument and every parent except the last one.

public static SPWeb SPWebParentWebGenerationDp( SPWeb web, int generation ) {
    for ( int i = ; i < generation; ++i ) {
        SPWeb toDispose = web;
 
        if ( web != null )
            web = web.ParentWeb;
 
        if ( toDispose != null && toDispose != SPContext.Current.Web )
            toDispose.Dispose();
    }
    return web;
}