I was doing some reading regarding boxing/unboxing, and it turns out that if you do an ordinary String.Format()
where you have a value type in your list of object[]
arguments, it will cause a boxing operation. For instance, if you're trying to print out the value of an integer and do string.Format("My value is {0}",myVal)
, it will stick your myVal
int
in a box and run the ToString
function on it.
Browsing around, I found this article.
It appears you can avoid the boxing penalty simply by doing the .ToString
on the value type before handing it on to the string.Format function: string.Format("My value is {0}",myVal.ToString())
Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the common language runtime (CLR) boxes a value type, it wraps the value inside a System. Object instance and stores it on the managed heap. Unboxing extracts the value type from the object.
Boxing and unboxing is a essential concept in C#'s type system. With Boxing and unboxing one can link between value-types and reference-types by allowing any value of a value-type to be converted to and from type object.
During process of boxing and unboxing, it may be possible that the performance of conversion is being affected due the large number of items stored in a collection. I've done a bit of research over this and here is my conclusion. As a general conclusion, we can say that an object is equivalent to a 'void *' of c++.
Boxing & unboxing is the process of converting a primitive value into an object oriented wrapper class (boxing), or converting a value from an object oriented wrapper class back to the primitive value (unboxing).
The compiler doesn't do this for you because string.Format
takes a params Object[]
. The boxing happens because of the conversion to Object
.
I don't think the compiler tends to special case methods, so it won't remove boxing in cases like this.
Yes in many cases it is true that the compiler won't do boxing if you call ToString()
first. If it uses the implementation from Object
I think it would still have to box.
Ultimately the string.Format
parsing of the format string itself is going to be much slower than any boxing operation, so the overhead is negligible.
1: yes, as long as the value-type overrides ToString()
, which all the inbuilt types do.
2: because no such behaviour is defined in the spec, and the correct handling of a params object[]
(wrt value-types) is: boxing
string.Format is just like any other opaque method; the fact that it is going to do that is opaque to the compiler. It would also be functionally incorrect if the pattern included a format like {0:n2}
(which requires a specific transformation, not just ToString()
). Trying to understand the pattern is undesirable and unreliable since the pattern may not be known until runtime.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With