18 September 2007

Boxing and unboxing

As everybody should know boxing and unboxing are tasks which take some valuable time. Of course we will not feel any different in invoking this function just couple times, but in case of hundred thousands invokes that can be noticeable. To build a faster programs I will describe couple good practices which you should be remember and use in this surface.
  • use overload methods for different arguments instead of using one which can accept only object argument

public virtual void DoIt(int i) { }

public virtual void DoIt(double d) { }

public virtual void DoIt(string s) { }

  • use generic types instead of using objects arguments

public List<int> collection = new List<int>();

  • overload methods ToString, Equals and ToHash in structurs to avoid boxing

struct TestStruct

{

public int ValueA;

public int ValueB;

public TestClass()

{

ValueA = 0;

ValueB = 0;

}

public override string ToString()

{

return String.Format("{0} {1}", this.ValueA, this.ValueB);

}

public override bool Equals(object obj)

{

if (obj == null)

return false;

if (this.GetType() != obj.GetType())

return false;

TestStruct comperable = (TestStruct)obj;

if (!this.ValueA.Equals(comperable.ValueA) || !this.ValueB.Equals(comperable.ValueB))

return false;

return true;

}

public override int GetHashCode()

{

return this.ValueA ^ this.ValueB;

}

}

0 Comments:

Post a Comment

<< Home