Class example:
public class SomeType
{
private int type;
// some code...
public override string ToString ()
{
if (type == 1) return "One";
if (type == 2) return "Two";
}
}
Now imagine application calls thousand times ToString() method in a second.
My question is: when I use inline created string in code like something = myClass.ToString() is in every call created a new string or compiler optimize it somehow? (because strings are immutable it could be returned only referense to a static string).
And if not, should I make static private string fields and return them in ToString method for performance reasons?
Ofcourse I will test it using Stopwatch, but I need an expert answer anyway.
You’re using string literals – which means you’re returning a reference to the same string each time. This is guaranteed by the language specification. From section 2.4.4.5 of the C# 5 specification:
So as a simpler example:
In your code, the
ToString()method will still be called – but it won’t create a new string object each time. You might consider using aswitchstatement instead of all thoseifstatements, by the way.Note that even if it did create a new string each time, creating thousands of strings per second won’t make a modern CPU break into a sweat. Both the allocator and garbage collector are pretty efficient, and modern computers can do an awful lot of work in a second.