By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,695 Members | 1,317 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,695 IT Pros & Developers. It's quick & easy.

advantage of boxing and unboxing

P: n/a
hi there,,

what is the real advantage of boxing and unboxing operations in csharp?
tried looking ard the internet but couldnt find any articles on it.

appreciate any help

Nov 28 '06 #1
Share this Question
Share on Google+
19 Replies


P: n/a
<ah*****@gmail.comwrote in message
news:11*********************@14g2000cws.googlegrou ps.com...
hi there,,

what is the real advantage of boxing and unboxing operations in csharp?
tried looking ard the internet but couldnt find any articles on it.
The advantage of boxing is that you can pass, say, an integer around as an
object. The advantage of unboxing is you get you native integer performance
back.

Michael
Nov 28 '06 #2

P: n/a
ah*****@gmail.com wrote:
what is the real advantage of boxing and unboxing operations in csharp?
tried looking ard the internet but couldnt find any articles on it.
You can have methods that take or return ANY type of value. How would
you implement Reflection's GetField or SetProperty methods without
boxing?

Secondarily, you can have data structures that can hold ANY type of
value, like an object[] or 1.x's ArrayList and HashTable.

--

..NET 2.0 for Delphi Programmers
www.midnightbeach.com/.net
What you need to know.
Nov 28 '06 #3

P: n/a
It takes a lot of resources, so it should be minimized.

Robin S.
---------------
<ah*****@gmail.comwrote in message
news:11*********************@14g2000cws.googlegrou ps.com...
hi there,,

what is the real advantage of boxing and unboxing operations in csharp?
tried looking ard the internet but couldnt find any articles on it.

appreciate any help

Nov 28 '06 #4

P: n/a
what resources does it take? and when you say 'it' takes a lot of
resources, would something as simple as the following take alot of
resources?

class Test
{
static void Main() {
int i = 123;
object o = i; //boxing
int j = (int) o; //unboxing
}
}

I ask as a complete beginner, thankyou for your time!

Gary.

RobinS wrote:
It takes a lot of resources, so it should be minimized.

Robin S.
---------------
<ah*****@gmail.comwrote in message
news:11*********************@14g2000cws.googlegrou ps.com...
hi there,,

what is the real advantage of boxing and unboxing operations in csharp?
tried looking ard the internet but couldnt find any articles on it.

appreciate any help
Nov 28 '06 #5

P: n/a
RobinS wrote:
>
It takes a lot of resources, so it should be minimized.
Not really. It does consume resources and is not free, so should be
minimized, but it certainly doesn't consume a "lot" of resources.

Boxing creates a reference type, on the heap, that contains the boxed
value and a type code. So, there's the modest cost of allocation
(which does push the system closer to the next garbage collection) and
the modest cost of copying data.

Unboxing copies the value type from the boxed value to a new copy of
the value type. So, there's the modest cost of copying the value type.

I did some tests a while back. Populating an ArrayList with integers,
then reading them all back, takes about twice as long as populating a
List<intwith integers and then reading them all back. A large ratio,
and one that can make a difference in a bottleneck routine, but not a
large absolute difference - neither operation is particularly slow.

--

..NET 2.0 for Delphi Programmers
www.midnightbeach.com/.net
What you need to know.
Nov 28 '06 #6

P: n/a
"RobinS" <Ro****@NoSpam.yah.nonewrote in message
news:M9******************************@comcast.com. ..
It takes a lot of resources, so it should be minimized.
Unless your app is doing pure processing it will make very little
difference.

Michael
Nov 28 '06 #7

P: n/a
No, something like the code you posted would not "take a lot of
resources".

IMHO, RobinS's post was too brief to the topic justice.

The only cases in which boxing / unboxing is likely to cause problems
are when:

1. You're doing it in bottleneck code. That is, code that is run deep
within nested loops and is CPU bound. A performance profiler will tell
you which methods in your program are taking up all the time. If you
look at one of the heavy-hitters and it's using Object and boxing and
unboxing then consider whether you can't change the design to do things
another way (like using generics) to avoid the extra time taken boxing
and unboxing.

2. You're doing it in a shared library and you're not sure whether the
code will be heavily used later on.

In my experience, boxing and unboxing becomes a problem only when it's
"deep down" into your software layers and you discover that your
program is creating millions of little boxed objects on the heap,
objects which the garbage collector later has to go and collect. In
other words, a harmless little routine that boxes a few hundred values
is just that: harmless. At least, it's harmless until you call it in
sixteen places within a higher-level class, which is then invoked in
seven places in a yet-higher-level class, which is then... and suddenly
you've got a half million boxed objects cluttering up memory.

The simple box and unbox that you posted, done once at the Main()
method level, is by comparison completely harmless.

In answer to your specific question, boxing / unboxing adds the
following costs:
1. The cost to box the value: allocate space for it on the heap and
copy the value to the allocated box.
2. The cost to unbox the value: one extra memory dereference in order
to find the exactly location of the value to copy off the heap.
3. Garbage collector costs to reclaim the box when it's no longer
needed.
In small quantities these costs are negligable. The only catch is that
it's very easy to do massive numbers of box / unbox operations in a few
short lines of code.

ga********@myway.com wrote:
what resources does it take? and when you say 'it' takes a lot of
resources, would something as simple as the following take alot of
resources?

class Test
{
static void Main() {
int i = 123;
object o = i; //boxing
int j = (int) o; //unboxing
}
}

I ask as a complete beginner, thankyou for your time!

Gary.

RobinS wrote:
It takes a lot of resources, so it should be minimized.

Robin S.
---------------
<ah*****@gmail.comwrote in message
news:11*********************@14g2000cws.googlegrou ps.com...
hi there,,
>
what is the real advantage of boxing and unboxing operations in csharp?
tried looking ard the internet but couldnt find any articles on it.
>
appreciate any help
>
Nov 29 '06 #8

P: n/a
In response to all the postings in response to this posting:
Sorry. I read a few books by Francesco Balena, and he
says that this should be minimized where possible. I went
back to find a specific reference, and this is one thing he
says that is confirmed by the other responses to this post:

In general, it doesn't make sense to compare the performance
of a method that uses boxing with a similar method that doesn't.
An informal benchmark shows that a tight loop that calls a function
that requires boxing can be up to 30 times slower than a loop that
doesn't use boxing. However, you must repeat the loop 10 million
times to see a meaningful difference in absolute terms, so in
practice you should worry about boxing only in time-critical
code sections.

So I apologize, and will be more careful in the future with
information that I post.

Robin S.
--------------------------------------
"RobinS" <Ro****@NoSpam.yah.nonewrote in message
news:M9******************************@comcast.com. ..
It takes a lot of resources, so it should be minimized.

Robin S.
---------------
<ah*****@gmail.comwrote in message
news:11*********************@14g2000cws.googlegrou ps.com...
>hi there,,

what is the real advantage of boxing and unboxing operations in csharp?
tried looking ard the internet but couldnt find any articles on it.

appreciate any help


Nov 30 '06 #9

P: n/a

RobinS wrote:
In response to all the postings in response to this posting:
Sorry. I read a few books by Francesco Balena, and he
says that this should be minimized where possible. I went
back to find a specific reference, and this is one thing he
says that is confirmed by the other responses to this post:

In general, it doesn't make sense to compare the performance
of a method that uses boxing with a similar method that doesn't.
An informal benchmark shows that a tight loop that calls a function
that requires boxing can be up to 30 times slower than a loop that
doesn't use boxing. However, you must repeat the loop 10 million
times to see a meaningful difference in absolute terms, so in
practice you should worry about boxing only in time-critical
code sections.

So I apologize, and will be more careful in the future with
information that I post.
Robin,

One of the things I like about this newsgroup is that while we do
encourage you to double-check before you post, nobody here is going to
flame you if you make a mistake. Instead, we'll just correct you, as we
did.

Some of the older newsgroups are filled with screamers who think that
it's their life mission to blast anyone who doesn't know as much as
they do on the topic at hand. So far in this group the posters seem to
remember that we were all once newbies and are correspondingly helpful
and patient. I pray that it stays that way. It's refreshing. :-)

Nov 30 '06 #10

P: n/a
RobinS wrote:
I apologize, and will be more careful in the future with
information that I post.
Good for you - a lot of people would neither have checked nor publicly
acknowledged their mistake.

--

..NET 2.0 for Delphi Programmers
www.midnightbeach.com/.net
What you need to know.
Nov 30 '06 #11

P: n/a
"Jon Shemitz" <jo*@midnightbeach.comwrote in message
news:45***************@midnightbeach.com...
RobinS wrote:
>I apologize, and will be more careful in the future with
information that I post.

Good for you - a lot of people would neither have checked nor publicly
acknowledged their mistake.

--

.NET 2.0 for Delphi Programmers
www.midnightbeach.com/.net
What you need to know.
-----------------------------

Thanks. I always admit it when I'm wrong.
It's good to have a skill. ;-)

Robin S.
Dec 1 '06 #12

P: n/a
"RobinS" <Ro****@NoSpam.yah.nonewrote in message
news:jo******************************@comcast.com. ..
Thanks. I always admit it when I'm wrong.
It's good to have a skill. ;-)
Your post could be described as incomplete instead of wrong. It's a common
mistake for programmers find that a technique is less efficient than another
and then go to extensive lengths to avoid using it.

Michael
Dec 3 '06 #13

P: n/a
Hi,
I have some code which I have reviewed with FXCop. FXCop does not like
all the boxing and unboxing I am doing, but I have not been able to figure
out a reasonable way to do things without it.
The situation is that I am gathering a lot of information from several
different sources (Web services) and relating it all back to Unique IDs. I
have made a Hashtable using the Unique ID as as the key and an object which
holds all my bits of data as an object in the Hashtable. So, when I get a new
bit of info, I get the object from the hashtable by the ID and then have to
recast it as the correct object type to add the info in.

Here is a snippet of code
Hashtable TempTable = (Hashtable) TheseNcbiData.Clone();
foreach (string giKey in TempTable.Keys)
{
NcbiData ThisData = (NcbiData) TheseNcbiData[giKey];
//Add the new data to this object.
//Save it back to the main Hashtable
}

I am not sure how to do this without implementing a Dictionary (Maybe that
is what I should not, but it seems like a pain. I have never used one....).
Any suggestions?
Thanks!
Ethan

Dec 4 '06 #14

P: n/a
Ethan Strauss <Et**********@discussions.microsoft.comwrote:
Hi,
I have some code which I have reviewed with FXCop. FXCop does not like
all the boxing and unboxing I am doing, but I have not been able to figure
out a reasonable way to do things without it.
The situation is that I am gathering a lot of information from several
different sources (Web services) and relating it all back to Unique IDs. I
have made a Hashtable using the Unique ID as as the key and an object which
holds all my bits of data as an object in the Hashtable. So, when I get a new
bit of info, I get the object from the hashtable by the ID and then have to
recast it as the correct object type to add the info in.

Here is a snippet of code
Hashtable TempTable = (Hashtable) TheseNcbiData.Clone();
foreach (string giKey in TempTable.Keys)
{
NcbiData ThisData = (NcbiData) TheseNcbiData[giKey];
//Add the new data to this object.
//Save it back to the main Hashtable
}

I am not sure how to do this without implementing a Dictionary (Maybe that
is what I should not, but it seems like a pain. I have never used one....).
Well, Dictionary isn't hard to use, but:

1) There's no boxing or unboxing involved in the above unless NcbiData
is a struct
2) It would probably be better to iterate through the *entries* in the
table, rather than just the keys, as you want to fetch the value for
each entry too.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 4 '06 #15

P: n/a


"Jon Skeet [C# MVP]" wrote:
Ethan Strauss <Et**********@discussions.microsoft.comwrote:
Hi,
I have some code which I have reviewed with FXCop. FXCop does not like
all the boxing and unboxing I am doing, but I have not been able to figure
out a reasonable way to do things without it.
The situation is that I am gathering a lot of information from several
different sources (Web services) and relating it all back to Unique IDs. I
have made a Hashtable using the Unique ID as as the key and an object which
holds all my bits of data as an object in the Hashtable. So, when I get a new
bit of info, I get the object from the hashtable by the ID and then have to
recast it as the correct object type to add the info in.

Here is a snippet of code
Hashtable TempTable = (Hashtable) TheseNcbiData.Clone();
foreach (string giKey in TempTable.Keys)
{
NcbiData ThisData = (NcbiData) TheseNcbiData[giKey];
//Add the new data to this object.
//Save it back to the main Hashtable
}

I am not sure how to do this without implementing a Dictionary (Maybe that
is what I should not, but it seems like a pain. I have never used one....).

Well, Dictionary isn't hard to use, but:

1) There's no boxing or unboxing involved in the above unless NcbiData
is a struct
2) It would probably be better to iterate through the *entries* in the
table, rather than just the keys, as you want to fetch the value for
each entry too.

--
Jon Skeet - <sk***@pobox.com>
Thanks Jon,
NcbiData IS a struct....
The reason I set it up iterating through the keys is that I don't have the
key value stored within the NcbiData object, I only know it by its
relationship with the object in the Hashtable. But that would be easy to
change.

I am still unclear on what is going on with Boxing. If NcbiData was a Class,
then I would not be boxing/unboxing? Could I deal with the issue by simply
making it a class? That seems wrong somehow, but I am not sure...
Ethan
Dec 4 '06 #16

P: n/a
Ethan Strauss <Et**********@discussions.microsoft.comwrote:
NcbiData IS a struct....
Ah. Any reason, out of interest? It's very rarely worth creating your
own structs, and
The reason I set it up iterating through the keys is that I don't have the
key value stored within the NcbiData object, I only know it by its
relationship with the object in the Hashtable. But that would be easy to
change.
You don't need the key within NcbiData - if you iterate through the
*entries* you get both the key and the value.
I am still unclear on what is going on with Boxing. If NcbiData was a Class,
then I would not be boxing/unboxing?
No, you wouldn't.
Could I deal with the issue by simply
making it a class? That seems wrong somehow, but I am not sure...
Well, that would change other semantics as well - you need to be very
clear whether you want reference type semantics or value type
semantics.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 4 '06 #17

P: n/a
Ethan Strauss <Et**********@discussions.microsoft.comwrote:
Ethan Strauss <Et**********@discussions.microsoft.comwrote:
NcbiData IS a struct....
Ah. Any reason, out of interest? It's very rarely worth creating your
own structs, and
NcbiData is a gathering of 5 or 6 different strings in a single package for
convenience. There are no methods or complexities associated with it.
Therefor it can be a struct. I assumed that a struct would be more effecient
than a class, but I really don't understand the difference. So, I guess the
real reason this is a struct is because it could be.
You really, really need to understand the difference between structs
and classes. It's not the same in C# as it is in some other languages.

I'm still working on a full article about the differences, but some of
them are explained at
http://www.pobox.com/~skeet/csharp/memory.html
and
http://www.pobox.com/~skeet/csharp/parameters.html

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 5 '06 #18

P: n/a
On Tue, 5 Dec 2006 18:45:17 -0000, Jon Skeet [C# MVP]
<sk***@pobox.comwrote:
>You really, really need to understand the difference between structs
and classes. It's not the same in C# as it is in some other languages.

I'm still working on a full article about the differences, but some of
them are explained at
http://www.pobox.com/~skeet/csharp/memory.html
and
http://www.pobox.com/~skeet/csharp/parameters.html
If only there were a really easy mnemonic way of thinking about the
differences...

--
Posted via a free Usenet account from http://www.teranews.com

Dec 5 '06 #19

P: n/a
Ben Newsam <be********@ukonline.co.ukwrote:
You really, really need to understand the difference between structs
and classes. It's not the same in C# as it is in some other languages.

I'm still working on a full article about the differences, but some of
them are explained at
http://www.pobox.com/~skeet/csharp/memory.html
and
http://www.pobox.com/~skeet/csharp/parameters.html

If only there were a really easy mnemonic way of thinking about the
differences...
I'm not sure there's much need for a mnemonic, is there? I don't think
it's too hard to remember after you've properly understood it once -
it's just a case of getting that understanding to start with.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 6 '06 #20

This discussion thread is closed

Replies have been disabled for this discussion.