c# toString() performance

喜你入骨 提交于 2019-12-08 17:19:04

问题


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?


回答1:


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();



回答2:


Yes. Creating a new instance of a class (as is being done with the string class in this case) will allocate memory for the instance.



来源:https://stackoverflow.com/questions/5920209/c-sharp-tostring-performance

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!