Performance test on empty string

 
 
  • Gérald Barré

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 almost no difference. The proof:

C#
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.

More recently, the JIT considers both value as strictly equals (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 check null values)

To know what is the quickest way, I did a little test. For this test 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 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.

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

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub