'Most performant way of checking empty strings in C# [closed]
What is the best way for checking empty strings (I'm not asking about initializing!) in C# when considering code performance?(see code below)
string a;
// some code here.......
if(a == string.Empty)
or
if(string.IsNullOrEmpty(a))
or
if(a == "")
any help would be appreciated. :)
Solution 1:[1]
I think the best way is if(string.IsNullOrEmpty(a)) because it's faster and safer than the other methods.
Solution 2:[2]
string.IsNullOrEmpty(a)
it will check both NULL || EMPTY
this is the Implementation :
public static bool IsNullOrEmpty(string value)
{
if (value != null)
{
return (value.Length == 0);
}
return true;
}
Solution 3:[3]
A late arrival:
if a == ""
will give rise to Code Analysis warning CA1820, so you definitely shouldn't do that. For a full analysis see CA1820: Test for empty strings using string length
Solution 4:[4]
Create an extension method for complete check:
public static bool IsEmpty(this string s)
{
if(s == null) return true;
return string.IsNullOrEmpty(s.Trim()); // originally only (s)
}
Sorry, not good code, fixed. Now this will tell you, if the string is empty or if is empty after trimming.
Solution 5:[5]
You can use Length as well
string input = "";
if (input != null)
{
if (input.Length == 0)
{
}
}
Solution 6:[6]
String.Empty value will be deciphered at run time only but on the other side "" value is known at the compile time itself.
That's the only difference between those two.
But coming to the best practice, if tomorrow M$ decides that the empty string value should be used as '' instead of "" due to some reason, then your code has to be changed every where. So in that case its best to use String.Empty.
Its the same practice used with Path.Combine as well.
Solution 7:[7]
This is covered and documented in the official code analysis rule CA1820: Test for empty strings using string length.
Comparing strings using the String.Length property or the String.IsNullOrEmpty method is faster than using Equals. This is because Equals executes significantly more MSIL instructions than either IsNullOrEmpty or the number of instructions executed to retrieve the Length property value and compare it to zero.
So to check whether a string is empty, use a .Length 0 check (string.Length property):
"".Length == 0
If the string variable may be null, use string.IsNullOrEmpty().
If you want to interpret and accept whitespace as “empty”, use string.IsNullOrWhiteSpace().
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | budi |
| Solution 2 | |
| Solution 3 | Dave |
| Solution 4 | |
| Solution 5 | John Odom |
| Solution 6 | Zenwalker |
| Solution 7 | Kissaki |
