C # performance toString ()

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

 object height = 10; string heightStr = height.ToString(); 

When I call ToString() on height , I return the type of the string. Is the runtime memory allocation for this line?

+6
source share
2 answers

Yes, the runtime will allocate memory for any string object that you create or query, including one that returns from a method call.

But no, that’s absolutely not what you need to worry about. This will not have a noticeable effect on the performance of your application, and you should never be tempted to prematurely optimize your code.

Int32.ToString method Int32.ToString very fast. It calls native code written at the CLR level, which is unlikely to be a performance bottleneck in any application.


In fact, the real performance issue here will be boxing , which is the process of converting the type of a value into an enter object and back. This will happen because you declared the variable height as the type object , and then assigned it an integer value.

It is best to declare height explicitly as an int type, for example:

 int height = 10; string heightStr = height.ToString(); 
+6
source

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

+4
source

Source: https://habr.com/ru/post/887508/


All Articles