Performance test on empty string

Today I will talk about strings, and more particularly about empty strings (or if you prefer string containing zero characters).

First question: What is the difference between "" and string.Empty ?

Since the .NET 2.0, there is no difference. The proof:

string s1 = "";
string s2 = string.Empty;
Console.WriteLine(ReferenceEquals(s1, s2)); //true

With .NET 1.1, the difference is at the allocation level. "" creates a string while string.Empty using the pre-created string.

Second question: How to test if a string is empty?

There are four ways to do this:

  • Equality test: str == "" ou str == string.Empty
  • Reference test Object.ReferenceEquals(str, string.Empty)
  • Test on the length: str.Length == 0
  • Using the function: String.IsNullOrEmpty(str) (not exactly the same as it also check null values)

To know what is the quickest way, I did a little test. For this test I used two strings:

string s1 = string.Empty;
string s2 = "foobar";

Here is a table with all the results. The times displayed are in seconds, and are calculated for 2147483647 (int.MaxValue) iterations:

s1 (x86)s2 (x86)s1 (x64)s2 (x64)
str == string.Empty11782186981501218200
Object.ReferenceEquals966896501032410363
Length == 0139021430696049676
String.IsNullOrEmpty869987681121412128

As can be seen the difference is minimal and depends on the intended architecture. Unless one million comparisons are made, all methods are equivalents. So choose the one you find the most readable.

Leave a reply