This example uses three strings to compare different methods for determining whether a string is blank. One of the methods, the string class’s IsNullOrWhiteSpace method, only works in .NET Framework 4.5 or later, so this example targets that version of the Framework and uses Visual Studio 2013. (Visual Studio 2012 can also target that version of the Framework, but I don’t have it installed right now.)
The program uses the following code to initialize the three strings.
string string1 = "", string2 = "ABCD", string3;
For the entered number of trials and for each method, the code tests string1 and string2 to see which is empty. The program checks both strings in case there’s a difference in performance testing blank strings and non-blank strings.
The following code shows the tests that the program performs.
if (string1 == string.Empty) string3 = string1; if (string2 == string.Empty) string3 = string2; ... if (string1.CompareTo(string.Empty) == 0) string3 = string1; if (string2.CompareTo(string.Empty) == 0) string3 = string2; if (string1 == "") string3 = string1; if (string2 == "") string3 = string2; if (string1.Length == 0) string3 = string1; if (string2.Length == 0) string3 = string2; if (string.IsNullOrEmpty(string1)) string3 = string1; if (string.IsNullOrEmpty(string2)) string3 = string2; if (string.IsNullOrWhiteSpace(string1)) string3 = string1; if (string.IsNullOrWhiteSpace(string2)) string3 = string2;
If you look closely at the picture, you’ll see that testing the string’s Length property and IsNullOrEmpty are the fastest. Using == to compare a string to string.Empty and "" took a bit longer. The IsNullOrWhitespace method took a longer still. Surprisingly the CompareTo method took more than 25 times as long!
Keep in mind that the tests were performed a huge number of times (100 million times in this test) so the total amount of time used is tiny. The CompareTo method is slow and isn’t all that readable, so you probably shouldn’t use it. The IsNullOrEmpty method is slightly more readable.
I usually use one of the == tests because they provide a good balance between readability and performance.