Performance test on empty string

 
 
  • Gérald Barré

This post covers strings, focusing specifically on empty strings (strings containing zero characters).

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

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

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

With .NET 1.1, the difference was at the allocation level. "" created a new string while string.Empty used the pre-created one.

More recently, the JIT considers both values as strictly equal (JIT: Import string.Empty as "", Delete code related to CompilationRelaxations.NoStringInterning).

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

There are four ways to do this:

  • Equality test: str == "" or 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 checks null values)

To find the quickest approach, I ran a small benchmark. I used two strings:

C#
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 you can see, the difference is minimal and depends on the target architecture. Unless millions of comparisons are made, all methods are equivalent. Choose whichever you find most readable.

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?