What is the best way for checking empty strings (I\'m not asking about initializing!) in C# when considering code performance?(see code bel
Do not compare strings to String.Empty
or ""
to check for empty strings.
Instead, compare by using String.Length == 0
The difference between string.Empty
and ""
is very small. String.Empty
will not create any object while ""
will create a new object in the memory for the checking. Hence string.empty is better in memory management.
But the comparison with string.Length == 0
will be even faster and the better way to check for the empty string.
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.
You can use Length as well
string input = "";
if (input != null)
{
if (input.Length == 0)
{
}
}
I think the best way is if(string.IsNullOrEmpty(a))
because it's faster and safer than the other methods.
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
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;
}