473,386 Members | 1,791 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

advantage of boxing and unboxing

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
19 13661
<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
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
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
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
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
"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
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
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

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
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
"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
"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
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
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


"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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

43
by: Mountain Bikn' Guy | last post by:
I have a situation where an app writes data of various types (primitives and objects) into a single dimensional array of objects. (This array eventually becomes a row in a data table, but that's...
3
by: Steve | last post by:
Hi, I have a class like: public ClassA { int vals1; int vals2; }
24
by: ALI-R | last post by:
Hi All, First of all I think this is gonna be one of those threads :-) since I have bunch of questions which make this very controversial:-0) Ok,Let's see: I was reading an article that When...
94
by: Peter Olcott | last post by:
How can I create an ArrayList in the older version of .NET that does not require the expensive Boxing and UnBoxing operations? In my case it will be an ArrayList of structures of ordinal types. ...
161
by: Peter Olcott | last post by:
According to Troelsen in "C# and the .NET Platform" "Boxing can be formally defined as the process of explicitly converting a value type into a corresponding reference type." I think that my...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.