by skeet via Jon Skeet: Coding Blog on 10/8/2008 7:42:02 PM
I'm currently reading the (generally excellent) CLR via C#, and I've recently hit the section on boxing. Why is it that authors feel they have to scaremonger about the effects boxing can have on performance?
Here's a piece of code from the book:
In the text afterwards, he reiterates the point:
This second version executes much faster and allocates less memory from the heap.
This seemed like an overstatement to me, so I thought I'd try it out. Here's my test application:
I compiled the code with one symbol defined each time, with optimisations and without debug information, and ran it from a command line, writing to nul (i.e. no disk or actual console activity). Here are the results:
nul
So, what do we learn from this? Well, a number of things:
Now I don't want anyone to misunderstand me - I agree that boxing is less efficient than not boxing, where there's a choice. Sometimes (as here, in my view) the "more efficient" code is slightly less readable - and the efficiency benefit is often negligible compared with other factors. Exactly the same thing happened in Accelerated C# 2008, where a call to Math.Pow(x, 2) was the dominant factor in a program again designed to show the efficiency of avoiding boxing.
Math.Pow(x, 2)
The performance scare of boxing is akin to that of exceptions, although I suppose it's more likely that boxing could cause a real performance concern in an otherwise-well-designed program. It used to be a much more common issue, of course, before generics gave us collections which don't require boxing/unboxing to add/fetch data.
In short: yes, boxing has a cost. But please look at it in context, and if you're going to start making claims about how much faster code will run when it avoids boxing, at least provide an example where it actually contributes significantly to the overall execution cost.
Original Post: Why boxing doesn't keep me awake at nights
The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.