Monday, March 29, 2010

Tips for avoiding unnecessary boxing and unboxing

Boxing and unboxing can add overhead to runtime operations. You should especially try to avoid boxing and unboxing when you are performing compute intensive, repetitive tasks. Observing the following three tips will help eliminate unnecessary boxing and unboxing.

  • Implement type specific, overloaded versions of functions. So if a function is often called with a particular type of argument, then create specific version of the function that accepts that type of parameter. (Instead of just creating one version that selects an Object argument)
  • Use generics when ever possible instead of accepting Object arguments.
  • Override the ToString, Equals, and GetHash virtual members when defining structures.

Additional Resources
Boxing and Unboxing (David Cumps)

No comments:

Post a Comment