3/02/2010

String.Empty vs “” vs String. IsNullOrEmpty

I was reading up on this recently and a couple of interesting points came to light:

myString = “” creates a new instance of type String.

myString = String.Empty does not.

The key item is doing comparisons. Here’s some sample test code:


  
class Program {
static void Main(string[] args)
{
String myString = "";
long a, b, c, d, e, f;
Console.WriteLine("Method 1...");
a = DateTime.Now.Ticks;
for (int index = 0; index < 100000000; index++)
{
bool isEmpty = myString == "";
}
b = DateTime.Now.Ticks;
Console.WriteLine("Method 2...");
c = DateTime.Now.Ticks;
for (int index = 0; index < 100000000; index++)
{
bool isEmpty = myString.Length == 0;
}
d = DateTime.Now.Ticks;
Console.WriteLine("Method 3...");
e = DateTime.Now.Ticks;
for (int index = 0; index < 100000000; index++)
{
bool isEmpty = String.IsNullOrEmpty(myString);
}
f = DateTime.Now.Ticks;
var Method1 = b - a;
var Method2 = d - c;
var Method3 = f - e;
Console.WriteLine("Method 1: bool isEmpty = myString == \"\" took {0} ticks", Method1);
Console.WriteLine("Method 2: bool isEmpty = myString.Length == 0; took {0} ticks", Method2);
Console.WriteLine("Method 3: bool isEmpty = String.IsNullOrEmpty(myString) took {0} ticks", Method3);
Console.Read();
}
}



The results:

Method 1: bool isEmpty = myString == "" took 4836000 ticks
Method 2: bool isEmpty = myString.Length == 0; took 2340000 ticks
Method 3: bool isEmpty = String.IsNullOrEmpty(myString) took 3744000 ticks

Bottom Line? The consensus among at least 4 or 5 expert Tweeters who commented was, IsNullOrEmpty is worth the extra ticks to test for null, even with 10 million iterations in the test!

Note: At the request of Todd Spatafore, I did a Visual Studio 2010 .NET 4.0 app that adds “String.IsNullOrWhitespace”. It performed the worst of all. You can download the VS2010 test solution here:

N.B. Jeremy commented to try:


I did this and it actually ran faster than bool isEmpty =myString.Length == 0;

so you could use this and achieve the need to test for null, and still be the fastest of the three methods shown.