Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling ToString() To Prevent Boxing

Tags:

c#

boxing

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.

enter image description here

like image 560
David Klempfner Avatar asked Jun 18 '14 04:06

David Klempfner


People also ask

Is ToString a boxing?

This shows that there is no boxing in the call i. ToString() , but there is boxing in the call i. GetType() .

What happens if you call ToString on a string?

The toString() method returns a string as a string. The toString() method does not change the original string.

Why do we use ToString in C#?

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.

How do I convert ToString?

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.


1 Answers

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.

like image 60
vesan Avatar answered Oct 21 '22 07:10

vesan