8

To check whether a string is empty I use

var test = string.Empty; 
if (test.Length == 0) Console.WriteLine("String is empty!");
if (!(test.Any())) Console.WriteLine("String is empty!");
if (test.Count() == 0) Console.WriteLine("String is empty!");
if (String.IsNullOrWhiteSpace(test)) Console.WriteLine("String is empty!");
  1. All the above statements produces the same output. What is the optimal method that I should use?

    var s = Convert.ToString(test);    
    s = test.ToString(CultureInfo.InvariantCulture);
    
  2. Again, both statements does the same thing. What is the best method to use?

I tried debugging and how to benchmark the performance of a C# statement?

J. Steen
  • 15,470
  • 15
  • 56
  • 63

4 Answers4

10

First of all the 4 statemens are not giving the same output on all inputs. Try null and the first 3 will throw an exception. And try whithspaces the last one will give you a failty result. So you really have to think about what you want. The best way to go are normally the:

string.IsNullOrEmpty
string.IsNullOrWhiteSpace

Only if you are doing this a few million times you should have a look on how to optimize your code further.

Here some test result, but this can differ on any .net version:

Test results for 100 million iterations:

Equality operator ==:   796 ms 
string.Equals:          811 ms 
string.IsNullOrEmpty:   312 ms 
Length:                 140 ms  [fastest]
Instance Equals:       1077 ms 

source

Peter
  • 27,590
  • 8
  • 64
  • 84
3

I would go for String.IsNullOrWhiteSpace or String.IsNullOrEmpty.

Length, Count and Any could fail if test is null with object null reference]

Update

Unless you are sure your string won't be null, then you will have to check if string is null before testing the length or count or calling any method on the variable.

In these scenario, .Length is not the same as String.IsNullOrWhiteSpace

string test = "    ";
test.Length == 0;  //false
String.IsNullOrWhiteSpace(test); //true
codingbiz
  • 26,179
  • 8
  • 59
  • 96
  • That means, an exception will be thrown if the string is null. So to avoid exception handling, it is better to go with IsNullorWhiteSpace ? – now he who must not be named. Nov 07 '12 at 09:25
  • Unless you are sure `test` must have a value, `String.IsNullOrEmpty` is safer – codingbiz Nov 07 '12 at 09:27
  • But, IsNullorWhiteSpace checks for null, whitespace and empty string, should it be better If I use it instead of IsNullorEmpty ? – now he who must not be named. Nov 07 '12 at 09:28
  • that would depend on your application. Tab and Enter are not possible in a single line textbox. If you pressed tab, it would go to the next control, if you pressed enter, it would submit the form or do nothing. If you don't want use to press spacebar as valid input, you would use `IsNullorWhiteSpace` which can also achieve with `Trim()`. That depends on which is convenience. If spaces are allowed, `IsNullOrEmpty` is enough – codingbiz Nov 07 '12 at 09:35
1

As far as I'm aware:

.Any(): has the intent of checking whether any objects exist in an array. And since string is an array of char, this works. And is part of Linq

.Length: has the intent of giving you the length of the array of char.

So, yes the same behavior, but slightly different intents.

BTW, you should really use String.IsNullOrWhitespace to check strings as empty. At least that is my preference so that if you have a string of many whitespace characters you don't have to trim first.

Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
1

For one variable, results are:

  1. String.IsNullOrEmpty(test) < String.IsNullOrWhiteSpace(test) << test.Length==0 <<< !(test.Any())test.Count() == 0
  2. test.ToString(CultureInfo.InvariantCulture) < Convert.ToString(test) (Order of 10 times)

I used the following code snippet to test the above.

static void Main(string[] args)
    {
        var test = string.Empty;
        System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
        sw.Start();
        if (test.Length == 0)
        {
            sw.Stop();
            Console.WriteLine("String is empty!  " + sw.ElapsedTicks);
        }
        sw.Restart();
        if (!(test.Any()))
        {
            sw.Stop();
            Console.WriteLine("String is empty!  " + sw.ElapsedTicks);
        }
        sw.Restart();
        if (String.IsNullOrWhiteSpace(test))
        {
            sw.Stop();
            Console.WriteLine("String is empty!  " + sw.ElapsedTicks);
        }
        sw.Restart();
        if (String.IsNullOrEmpty(test))
        {
            sw.Stop();
            Console.WriteLine("String is empty!  " + sw.ElapsedTicks);
        }
        sw.Restart();
        if (test.Count() == 0)
        {
            sw.Stop();
            Console.WriteLine("String is empty!  " + sw.ElapsedTicks);
        }
        sw.Restart();
        var s = Convert.ToString(test);
        sw.Stop();
        Console.WriteLine("String is empty!  " + sw.ElapsedTicks);
        sw.Restart();
        s = test.ToString(CultureInfo.InvariantCulture);
        sw.Stop();
        Console.WriteLine("String is empty!  " + sw.ElapsedTicks);
        Console.ReadKey();
    }

Infact String.IsNullOrEmpty(test) is the best as pointed out by somebody in the comments above... :)

Viral Jain
  • 1,004
  • 1
  • 14
  • 30