Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# toString() performance

Tags:

c#

.net

tostring

I'm curious about the ToString() method in C#. Take for example the following:

object height = 10;

string heightStr = height.ToString();

When I call ToString() on height, I get a string type back. Is the runtime allocating memory for this string?

like image 980
Andy Avatar asked May 07 '11 09:05

Andy


1 Answers

Yes, the runtime is going to allocate memory for any string object that you create or request, including one that is returned from a method call.

But no, this is absolutely not something that you have to worry about. It will not have any noticeable effect on the performance of your application, and you should never give in to the temptation to optimize code prematurely.

The Int32.ToString method is extremely quick. It calls down to native code written at the level of the CLR, which is not likely to be a performance bottleneck in any application.


In fact, the real performance problem here is going to be boxing, which is the process of converting a value type to type object and back again. This will occur because you declared the height variable as type object, and then assigned an integer value to it.

It is a far better idea to declare height explicitly as type int, like so:

int height = 10;
string heightStr = height.ToString();
like image 96
Cody Gray Avatar answered Sep 18 '22 21:09

Cody Gray