apocalypse
apocalypse

Reputation: 5884

ToString method and return static string

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.

Upvotes: 2

Views: 411

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502296

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:

When two or more string literals that are equivalent according to the string equality operator (§7.10.7) appear in the same program, these string literals refer to the same string instance.

So as a simpler example:

string x = "One";
string y = "One";
Console.WriteLine(object.ReferenceEquals(x, y)); // Prints True

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 a switch statement instead of all those if statements, 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.

Upvotes: 6

Related Questions