- For types that implement IDisposable, use the using.
- For rest of the types (think about implementing IDisposable for them if they are custom), use try/finally and call Dispose method in the finally block.
- Difference between calling the Close method for those types that implement it and Dispose is that the Close method does not call GC.SuppressFinalize() and therefore leaves the objects in memory longer (until finalizers are called). Use Dispose when you can.
- Minimize garbage collection with the following:
- if you are creating the same object with the same settings in a method frequently, see if you can create an attribute (member variable) and initialize it with a constructor instead (do not forget to implement IDisposable on the class and dispose of this variable when the object is destroyed).
before:
void TestMethod()
{
using(MyObject obj = new MyObject(CONST_ONE))
{
DoStuff(obj);
}
}
after:
private readonly MyObject obj = new MyObject(CONST_ONE);
void TestMethod()
{
DoStuff(obj);
}
- see if you can create static member variable as well.
{
private static MyObject _objOne;
public static MyObject ObjOne
{
get
{
if(_objOne == null) _objOne = new MyObject(CONST_ONE);
return _objOne
}
}
private static MyObject _objTwo;
public static MyObject ObjTwo
{
get
{
if(_objTwo == null) _objTwo = new MyObject(CONST_TWO);
return _objTwo
}
}
}
before:
void TestMethod()
{
using(MyObject obj = new MyObject(CONST_ONE))
{
DoStuff(obj);
}
}
after:
void TestMethod()
{
DoStuff(MyObject.ObjOne);
}
- see if you can implement a Builder pattern on one of these member variable objects
No comments:
Post a Comment