Boxing is considered slow because it implies the allocation of an object. In your case that object is short lived (will probably not survive Gen0), which makes it cheap. A recent microbenchmark I did put the cost of generating a short lived object at about ~15 CPU cycles. Cost might be a bit higher in real applications, but that boxing isn’t that expensive.
You should avoid allocations in performance critical code. But that means code that’s called >10 million times per second.
If you benchmark your above code, you’ll see that Console.WriteLine
is the expensive part, and that optimizing out those two boxes has negligible impact.
When optimizing a program’s performance, I’d:
- Profile to identify the bottleneck. But 99% of the code performance isn’t an issue
- Rewrite it to your hopefully better version
- Profile it again, and verify that the performance improvement is significant. If it is not, revert to the simpler code, or try another variation.
0
solved Boxing and Performance [closed]