Some methods can operate on either boxed or unboxed structures, while others can operate on structures only if they are boxed. If a method holds a boxed structure, it can pass that to methods which require boxed structures without having to box it. By contrast, if a method holds an unboxed structure, each call to a method which needs a boxed structure will require a separate boxing operation.
Consider:
interface IStooge { whatever };
struct Stooge : IStooge { whatever};
void Moe(Stooge x)
{
Larry(x);
}
void Larry<T>(T x) where T:IStooge
{
for (int i=0; i<1000000; i++)
Curly(x);
}
void Curly(IStooge x)
{ whatever; }
Moe has an unboxed Stooge
. Larry can work with either boxed or unboxed things that implement IStooge
. Curly only accepts boxed implementations of IStooge
.
If Moe
passes an unboxed Stooge
to Larry
, then Larry
is going to create a new boxed Stooge
, copy the data from x
to that, pass a reference to the new object to Curly
, and then abandon that new object; it will then repeat that process 999,999 more times, starting each time with a new boxed Stooge
.
If either Moe
had cast x
to IStooge
before passing it, or if Larry
were (like Curly
) a non-generic method that only accepted boxed implementations of of IStooge
, then x
would have been boxed before the call to Larry
. On each pass through the loop, Larry
would pass Curly
a reference to the already-boxed Stooge
, rather than having to create a new boxed instance. The net effect would be that the number of boxing operations required would be reduced enormously by either making Larry
non-generic or using it in non-generic fashion.
In cases where generics can eliminate boxing (they usually can), they naturally reduce boxing. In cases where boxing is going to end up being necessary, however, it's often better to do it in an outer scope rather than a nested one. Generics often prevent boxing in outer scopes, which is good in the cases where it can be prevented altogether, but not so good if it ends up moving it from someplace where it could be done once to someplace it will have to be done repeatedly.