Given a string ‘s’, which of the following expressions is faster?

1. String.IsNullOrEmpty( s )

2. s == null || s.Length == 0

If you guessed option #2, you are correct. As you might expect, it takes about 15% more time to call the IsNullOrEmpty method, but this represents only about one second per hundred million executions.

Here is a simple C# console program that compares the two options:

```using System;

namespace StringNullEmpty
{
class Program
{
static void Main( string[] args )
{
long loop = 100000000;
string s = null;
long option = 0;
long empties1 = 0;
long empties2 = 0;

DateTime time1 = DateTime.Now;

for (long i = 0; i < loop; i++)
{
option = i % 4;
switch (option)
{
case 0:
s = null;
break;
case 1:
s = String.Empty;
break;
case 2:
s = "H";
break;
case 3:
s = "HI";
break;
}
if (String.IsNullOrEmpty( s ))
empties1++;
}

DateTime time2 = DateTime.Now;

for (long i = 0; i < loop; i++)
{
option = i % 4;
switch (option)
{
case 0:
s = null;
break;
case 1:
s = String.Empty;
break;
case 2:
s = "H";
break;
case 3:
s = "HI";
break;
}
if (s == null || s.Length == 0)
empties2++;
}

DateTime time3 = DateTime.Now;

TimeSpan span1 = time2.Subtract( time1 );
TimeSpan span2 = time3.Subtract( time2 );
Console.WriteLine( "(String.IsNullOrEmpty( s )): Time={0} Empties={1}",
span1, empties1 );
Console.WriteLine( "(s == null || s.Length == 0): Time={0} Empties={1}",
span2, empties2 );
}
}
}```

The program output was:

(String.IsNullOrEmpty( s )): Time=00:00:06.8437500 Empties=50000000
(s == null || s.Length == 0): Time=00:00:05.9218750 Empties=50000000

Note this test is unscientific, and times may vary slightly with each run and of course from PC to PC.

The time difference is minimal enough that you can safely choose either option. You may actually prefer IsNullOrEmpty because it’s more intuitive. And the rumor about IsNullOrEmpty crashing is much ado about nothing.

Share and Enjoy: