With the following code snippet:
public static void Main()
{
int v = 2;
Console.WriteLine("number" + "," + v);
}
Apparently it's better to replace v
with v.ToString()
in the call to WriteLine()
to prevent the value type from being boxed.
However calling ToString()
still allocates an object on the heap, as would boxing the value type.
So what is the benefit of using v.ToString()
rather than letting it be boxed?
Update:
Looks like int.ToString()
is called before passing the value to string.Concat()
with or without explicitly calling int.ToString()
yourself.
I checked the CIL for with and without ToString()
and they're identical.
This shows that there is no boxing in the call i. ToString() , but there is boxing in the call i. GetType() .
The toString() method returns a string as a string. The toString() method does not change the original string.
Object. ToString is the major formatting method in the . NET Framework. It converts an object to its string representation so that it is suitable for display.
Convert the specified value to its equivalent string using the ToString() method. Initialize a bool value. bool boolVal = false; Now, to convert it to a string, use the ToString() method.
ToString()
will only box a variable if its type has no override of ToString()
(so it has to go to the implementation on the Object
class). However, int
does have an overridden ToString()
(see http://msdn.microsoft.com/en-us/library/6t7dwaa5(v=vs.110).aspx), so this does not happen.
The boxing is actually performed by the +
operator, because that just calls string.Concat
, which expects parameters of type Object
(or string
, depending on which overload is used). Therefore, integers have to be boxed for the call. Then, the string.Concat
method unboxes the int
again and calls ToString()
. Therefore, if you call it yourself, you'll save time by not having to do the boxing and unboxing.
There is a performance gain, although in most cases it will be quite marginal.
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