Sometime back I had blogged about using reference comparison to speed up ordinal string comparisons. Essentially this means that if you know for sure that your string is interned and you want to do an ordinal string comparison you can use the following optimization

if (command == "START")

Console.WriteLine("Starting Build...");

else if (command == "STOP")

Console.WriteLine("Stopping Build...");


// Optimization

if (Object.ReferenceEquals(command,"START"))

Console.WriteLine("Starting Build...");

else if (Object.ReferenceEquals(command, "STOP"))

Console.WriteLine("Stopping Build...");

This works only if the string command is an interned string. If its not (e.g. its accepted from command lines or is constructed) you can intern it using something like string internedCmd = string.IsInterned(command) ?? string.Intern(command); and then use the interned version of the same string.

However an email to the internal CSharp alias made me look again. The email stated that the static method String.Equals(a,b) is more efficient than instance method String.Equals(a). I looked in into the code and it appears that for static Equals we already do the reference comparison first, while for instance Equals we jump right to string comparison.

// Static Equals called from overloaded operator ==
public static bool Equals(string a, string b) { if ((object)a == (object)b) { return true; } if ((a != null) && (b != null)) { return string.EqualsHelper(a, b); } return false; }

This might get fixed in future .NET version when both Equals will do the reference comparison first. However, the optimization I suggested does not hold because its already been done in the framework right now.

So currently in the following snippet the second version is faster than the first

string a = ...;
string b = ...;

string.Equals(a, b); // faster