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********@mywa y.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******** *************@1 4g2000cws.googl egroups.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
>