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 ); Console.ReadLine(); } } }
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.
Errr…if you use the shiny new .NET symbols and debug into the framework from VS.NET 2008 you will see that in String.cs IsNullOrEmpty is really just:
public static bool IsNullOrEmpty(string value)
{
return (value == null || value.Length == 0);
}
So the small additional cost is really pushing and poping the stack etc.
Suggestion…edo your test using the Stopwatch Class instead of datetime.
[…] string = "" or = string.Empty? A short note on efficiency can be found here. https://www.csharp411.com/stringisnullorempty-shootout/ "Sami" wrote: > string = "" or string = string.Empty? > should is the […]
When compiling in release mode, the IsNullOrEmpty method is expanded inline, so the function call disappears and the gain no longer exists.
I just testing the same code but using
long loop = 5000000000;
and the following is the results
http://i54.tinypic.com/zles15.png