"Howard" <ho*******@yahoo.com> wrote:
Say I have something like this
string a = "123";
int number = (int)a;
int number = int.parse(a);
is the unboxing method int number = (int)a faster in this case?
thanks
This will not compile (try it). If the type of "a" was object (or if was
passed to the method I provided above), the cast would fail at runtime
with an InvalidCastException.
You can discover the type with a.GetType() or by testing "a is string"
etc.
The unboxing overhead relates to this:
object a = 4; // boxes an int
4 is a value type, native to the CPU. It isn't stored on the garbage
collected heap. All reference types are stored on the heap, however. In
order to make a "4" value fit into a reference type such as the most
general "System.Object" (object is an alias for System.Object), space
has to be made available on the heap, and the value needs to be copied
into this space. This process is called boxing. The reverse:
int i = (int) a; // where a is the object above
.... is called unboxing, and is the process of copying the value from the
heap back into a value type, where it can be optimized to (say) a CPU
register, for more efficient operations.
The overhead of this copying is the downside to the params object[]
approach. This overhead is the cost of allocating and initializing a
handful of bytes (around 8-12). In other words, it's relatively
insignificant, unless you're doing it in the middle of a very tight
loop.
-- Barry
--
http://barrkel.blogspot.com/