.netenumsclrboxing

Do boxing and unboxing have the same performance hit?


Do boxing and unboxing has the same performance hit? Or is unboxing faster, let's say?

(If yes, can you briefly explain the main reason.)


Solution

  • It partly depends what you mean by "unboxing". In IL terms, unboxing actually does slightly less than it does in C#. In C#, "unboxing" always involves copying the value somewhere, whereas in IL it only means checking the type of the box and making the value available that way.

    They've got different performance characteristics though: boxing requires the allocation of a new object, but no type checking.

    Unboxing at the IL level really only needs to check that the object you're trying to unbox really is a boxed value of the same type (or a compatible one). Then you need to add the value copy operation in C# version of unboxing.

    I would expect the allocation to be more expensive in the long run than the type check, particularly because there's not only the cost of allocating up-front, but the corresponding garbage collection hit later.

    As always, you should evaluate performance costs of operations in the context of your actual code. I don't expect the costs of boxing and unboxing to be significant in most modern .NET applications, where generics allow you to avoid them for collections etc.