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.)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.