C# string empty check(3 methods and efficiency)

Lionsure 2020-07-20 Original by the website

It is indispensable to deal with strings, and it is often necessary to judge whether the string is empty in the process of program development. What are the usual judgment methods and how efficient are the different methods?

There are usually three ways to determine whether a string is empty in C#, which are discussed below.

 

C# string empty check(3 methods and efficiency)

1. str.Length == 0

Using str.Length == 0, the efficiency of three methods is the highest, but it is prone to exceptions. When the string is empty, an exception occurs, such as

string str; or string str = null;

if(str.Length == 0) //Occur an exception

At this time, an exception occurs that the object cannot be empty.

 

If str is initialized beforehand, such as:

string str = "C# string empty check";

if(str.Length == 0) //No exception

At this time, no exception will occur. Therefore, if it can be concluded in advance that the string is not empty under any circumstances, this method can be used to improve efficiency; otherwise, it is not recommended.

 

2. str == string.Empty or str == ""

The efficiency of these two methods is slightly lower than str.Length == 0 , but no exception will be generated when the character is empty. Therefore, this method can be used if the variable is not initialized in advance, or it cannot be concluded that the variable must not be empty during the running of the program.

You may ask, str == string.Empty and str == "", which is more efficient? I remember that I discussed it in detail in the article "C# efficiency comparison of multiple strings concatenation". If you are interested, you can take a look, but I can tell you here: str == string.Empty is slightly higher.

 

3. str == string.IsNullOrEmpty

Null is usually used to check whether an object is empty, so this method can check whether the string(str) exists, or whether the string is empty(or ""). Compared with str == string.Empty, how efficient is it? Examples are as follows:

1) When the string is empty

string str = null;
       if (str == string.Empty)
       {
       }

if (string.IsNullOrEmpty(str))
       {
       }

2) When the string is not empty

string str = "C# string empty check";
       if (str == string.Empty)
       {
       }

if (string.IsNullOrEmpty(str))
       {
       }

By performing a comparison, in both cases, string.IsNullOrEmpty(str) is slightly faster than str == string.Empty.

Of course, this method of checking whether a string is empty has very little efficiency difference in the ordinary programming process. If it is not very complicated, it can be ignored. But try to use efficient methods.