[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 180
  • Last Modified:

Performance: Disposing/Releasing objects

I am a little confused by the Microsoft help on performance.

1. Do I need to dispose of a datatable?

myDataTable.Dispose();              Is it faster or slower to do this?

2. Do I need to create a dispose method for custom objects?

public class MyClass : IDisposable {
  public void Dispose() {
    Dispose(true);
    GC.SuppressFinalizer(this);
  }
  protected virtual void Dispose(bool disposing) {
    if (disposing) {
      ...
    }
      ...
  }

3. If I do create a dispose method for custom objects, then I should not implement Finalize(). Right?
0
mppeters
Asked:
mppeters
  • 2
2 Solutions
 
Razzie_Commented:
1. Alway call the Dispose() method when you don't need an object anymore, or else resources may never be freed.
2. You don't have to implement IDisposable if your custom objects do not use unmanaged resources. In general, if your custom object does not have members that implement IDisposable, your custom object does not need to do so.
3. Correct, since all resources are already freed when calling the dispose method.

HTH,

Razzie
0
 
mppetersAuthor Commented:
Thanks Razzie.

>>1. Alway call the Dispose() method when you don't need an object anymore, or else resources may never be freed.

In general if the object has a Dispose() method, I should call it.
Should I also be setting the disposed object to null?

>>2. You don't have to implement IDisposable if your custom objects do not use unmanaged resources. In general, if your custom object does not have members that implement IDisposable, your custom object does not need to do so.

Custom objects that do not use unmanaged resources do not need to implement IDisposable and therefore do not need to have a Dispose() method.

Should I be setting these custom object instances to null?
0
 
Razzie_Commented:
1. Nope, that doesn't matter.
2. Most of the time, that is not necessary. In some cases, it can even have a negative impact on performance. If you declare an object in a method, it is usually best to simply let it go out off scope without setting it to null.
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now