71

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. :)

joram
  • 143
  • 7
Allan Chua
  • 9,305
  • 9
  • 41
  • 61
  • I didn't searched yet. but I think it's different from the other because it includes the string.IsNullOrEmpty :) – Allan Chua Oct 24 '11 at 07:55
  • 15
    Trust me, no matter how unique you think your question is, just search first. – BoltClock Oct 24 '11 at 07:57
  • 3
    use `String.Empty` instead of "", "" is not recommended to use, because it allocated new string – Karel Frajták Oct 24 '11 at 07:58
  • 1
    Hi, I know and appreciate that you're trying to eliminate redundancy of questions here.. but im' really curious of this one :) thanks – Allan Chua Oct 24 '11 at 07:58
  • 13
    @Karel Frajtak: Uh, no, it does not allocate a new string. – BoltClock Oct 24 '11 at 07:58
  • @KarelFrajtak I think BoltClock is right – Allan Chua Oct 24 '11 at 08:06
  • 1
    @KarelFrajtak Check you facts please. That is **wrong**. – Otiel Oct 24 '11 at 08:15
  • 3
    Facts checked: As David implies, there difference between String.Empty and "" are pretty small, but there is a difference. "" actually creates an object, it will likely be pulled out of the string intern pool, but still… while String.Empty creates no object… so if you are really looking for ultimately in memory efficiency, I suggest String.Empty. However, you should keep in mind the difference is so trival you will like never see it in your cod. Cited from http://blogs.msdn.com/b/brada/archive/2003/04/22/49997.aspx – Karel Frajták Oct 24 '11 at 08:32
  • 1
    IsNullOrEmpty does not do the same thing though so you can not compare them on performance alone, the rest of the question is a dup – jk. Oct 24 '11 at 08:35
  • 1
    The one with which this q is marked as a duplicate is slightly different one. Voting to reopen.. – nawfal Jan 15 '14 at 17:10
  • 1
    Use whichever is more readable. `if(!a.Any())` is another option as well. – nawfal Jan 15 '14 at 17:11
  • 1
    Definitely **not a duplicate**: this one is about checking contents (that's **reading**, mostly combined with efficiency concerns), the other is about initialisation, resetting (**writing**). Most languages have an efficient empty check for strings, so a valid question for porting etc... – Wolf Dec 22 '16 at 10:38
  • I think: if(string.IsNullOrEmpty(a)) is a much better practice to get used to using. – Burgo855 Dec 26 '16 at 08:11
  • How did this question get closed as opinion-based? It's asking which method is faster. That's about as objective as you can get. At a horse race, it's not a matter of opinion about who won. Code is the same; as with horses, you can time how long it takes to run. Now it's possible that which method is faster depends on the execution environment, but even then it's likely that you could categorize "method A is fastest in scenario X". Voting to reopen. – Edward Brey Nov 04 '22 at 15:11

8 Answers8

120

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.

Wolf
  • 9,679
  • 7
  • 62
  • 108
Yogesh
  • 3,394
  • 9
  • 31
  • 46
  • 2
    I would not advice this method. If the string contains space(s), then the length of string would be greater then 0, and the test would then fail. – Mana Mar 09 '15 at 13:47
  • 58
    @Mana A string containing spaces is not empty. – Jim Balter Sep 11 '15 at 07:29
  • 5
    http://stackoverflow.com/a/151481/4767498 strings are interned so string.Empty and “” are equal now. – M.kazem Akhgary Dec 28 '15 at 06:05
  • @Mana I would agree with you. –  Jan 06 '16 at 21:27
  • @Shammy All the worse for you. str == "", str == String.Empty, and str.Length == 0 all have the same effect: they are true for empty strings and false for non-empty strings, which includes strings containing spaces. – Jim Balter Feb 18 '16 at 08:41
  • 1
    You could use "String.Trim().Length == 0" if you class white space as empty – Robin French Aug 16 '16 at 17:58
  • I wonder if the compiler just replaces a comparison to `""` with a comparison to `string.Empty`. – Dan Oct 18 '16 at 17:03
  • 1
    @Dan, the compiler replaces both `""` and `string.Empty` by the same constant. You can check that by changing the property via reflection - in newer versions it doesn't read the property. – Qwertiy Dec 22 '16 at 11:04
  • 1
    @Qwertiy It has varied over time as to whether `string.Empty` returns the same string as the empty string literal or returns its own string instance. There have been times throughout .NET's history where each has been true Of course, you shouldn't care; if you wrote a program that depends on either behavior you've done something wrong. But of course neither option will create new instances, they just have the potential to return a different cached instance. – Servy Dec 22 '16 at 18:31
  • 6
    string.Length == 0 gives an error if string is null... thus string.IsNullOrEmpty() is a better approach – Ricardo González Feb 15 '18 at 02:16
  • 1
    @DrYunke, it is better in one context, not all of them. In general, if you expect empty string, check for its emptiness, not nullness. Using `IsNullOrEmpty` might defer bugs detection, so use only when necessary and check for null is intended. Don't think of it as overall "better approach". – Mars Mar 26 '20 at 11:03
36

I think the best way is if(string.IsNullOrEmpty(a)) because it's faster and safer than the other methods.

budi
  • 6,351
  • 10
  • 55
  • 80
Gregory Nozik
  • 3,296
  • 3
  • 32
  • 47
  • 5
    No, it's slower than checking the string's length because it has to test two things rather than 1. – Eric J. Oct 24 '11 at 07:56
  • 4
    But if the string has null value the length check will fail I think – Gregory Nozik Oct 24 '11 at 08:00
  • 3
    True, but the OP asked about the fastest way to check for an empty string. Doing an extra check for null isn't the fastest way (possibly he knows the string will always be non-null). – Eric J. Oct 24 '11 at 08:03
  • @EricJ. I do think this is also a kind of slower than what i'm asking :) – Allan Chua Oct 24 '11 at 08:08
  • 2
    "if the string has null value the length check will fail I think" -- it will throw an Exception. (The other comments above are wrongheaded, since the OP's example uses an uninitialized variable, which will be null). – Jim Balter Sep 11 '15 at 07:36
  • @Jim Balter Since OP's example includes // some code here, we don't know if the variable is initialized or not. But since VS 2013 reports "CS0165: Use of unassigned local variable", I would assume it is initialized, although perhaps to null. – Andrew Dennison Mar 03 '17 at 17:47
  • @AndrewDennison You have a point ... my statement, "uses an uninitialized variable, which will be null" is incorrect. OTOH, this isn't actual code that the OP compiled, so no assumption about initialization is warranted. – Jim Balter Mar 04 '17 at 00:23
  • 1
    In general, if you expect empty string, check for its emptiness, not nullness. Using `IsNullOrEmpty` might defer bugs detection, so use only when necessary and check for null is intended. Don't treat it as a cure to NullReferenceException. When the day comes, you will be thankful that exception was thrown early. – Mars Mar 26 '20 at 11:08
20
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;
}
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • This checks for null in addition to the string being empty (2 checks) so will not be faster than checking the string's length only (and the OP did not ask about testing for either null or empty). – Eric J. Oct 24 '11 at 07:57
  • 1
    @EricJ. Yes, he did. And since he's checking a string that hasn't been set, he needs it ... he He explicitly referred to "not initializing" – Jim Balter Sep 11 '15 at 07:31
  • The actual code is slightly different: `return (value == null || value.Length == 0);`. [Source](http://referencesource.microsoft.com/#mscorlib/system/string.cs,8281103e6f23cb5c) – Maico Mar 10 '16 at 11:44
  • Whats the definition of empty? `""` i presume? – Sir Nov 05 '17 at 04:07
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

Dave
  • 3,429
  • 2
  • 26
  • 29
  • I gave you an upvote for adding a link to Microsoft Docs. The best answer is the official answer :) – joram May 23 '22 at 12:26
1

You can use Length as well

string input = "";

if (input != null)
{
    if (input.Length == 0)
    {

    }
}  
John Odom
  • 1,189
  • 2
  • 20
  • 35
1

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.

Karel Frajták
  • 4,389
  • 1
  • 23
  • 34
  • 10
    Why are you checking if the string is null twice? – Eric J. Oct 24 '11 at 07:58
  • 9
    @Eric J. He probably wants to be really really sure. – BoltClock Oct 24 '11 at 08:05
  • 2
    @Otiel, it is not - this is the decompiled body of `IsNullOrEmpty` method: `return value == null || value.Length == 0;` – Karel Frajták Aug 08 '13 at 15:23
  • 5
    As of .NET v4.0, you can use string.IsNullOrWhiteSpace, which will do the same thing faster. You could also add an extension method if you wish: `public static bool IsEmpty(this string s) { return string.IsNullOrWhiteSpace(s); }` – hypehuman Sep 09 '14 at 16:05
  • 1
    Note that extension methods that expect null break the usual semantics of the language. Consider the construct `something.IsEmpty()`. If `something` actually is null, calling methods on its type will always throw a `NullReferenceException`. It's possible to code extension methods with different behavior, but not without hurting code clarity. – Andrew Palmer Nov 22 '16 at 16:10
  • @Andrew Palmer. I think you meant to write: "calling methods on an instance will always throw a NullReferenceException." – Andrew Dennison Mar 03 '17 at 17:34
  • 2
    @Andrew Palmer. I don't agree that string.IsNullOrEmpty(s) is any more clear than s.IsNullOrEmpty., especially if the extension method name indicates it can handle a null. – Andrew Dennison Mar 03 '17 at 17:39
  • @AndrewDennison No. Your correction is not correct. There is NOT an instance of anything! The variable is null. This is what I mean by the confusion this creates. The syntax creates the illusion you are working with an instance. – Andrew Palmer Mar 03 '17 at 18:59
  • @AndrewPalmer You wrote "calling methods on its type", which is nonsense; you should have just written "calling methods on it". And one specific use of extension methods is for values that can be null; there's no confusion when the method name contains "IsNull", unless one insists on being confused for no reason. – Jim Balter Mar 04 '17 at 00:34
  • @JimBalter I do apologize for the wording you excerpted, which was poorly expressed. (If I could edit a comment, I would.) To respond, there's, of course, no requirement in the language that enforces verbiage such as "IsNull" in the name of your extension methods that allow null, and the `.IsEmpty(s)` example suffers from this exact issue of clarity. I certainly still maintain that's confusing and poor style. I do, personally, also object to `s.IsNullOrEmpty()`. `string.IsNullOrEmpty(s)` is abundantly clear, and doesn't have to break with standard object-oriented semantics. – Andrew Palmer Mar 04 '17 at 21:02
  • "To respond, there's, of course, no requirement in the language that enforces verbiage such as "IsNull" in the name of your extension methods that allow null, and the .IsEmpty(s) example suffers from this exact issue of clarity." -- this is ridiculous and not intellectually honest. Of course the language doesn't require that methods have sensible and meaningful names. That IsEmpty suffers from clarity means that it's a bad name and shouldn't be used; it has no bearing on what we are discussing. – Jim Balter Mar 04 '17 at 23:22
0

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.

Zenwalker
  • 1,883
  • 1
  • 14
  • 27
  • 1
    If Microsoft changes the definition of string.Empty, millions of programs worldwide will break. – Eric J. Oct 24 '11 at 08:13
  • 1
    _if tomorrow M$ decides that the empty string value should be used as '' instead of ""_. That day, Microsoft will be very dumb. And what if they decide to rename `String.Empty`? – Otiel Oct 24 '11 at 08:14
  • Your right, but lets be on safer side when there is an alternative :) – Zenwalker Oct 24 '11 at 08:14
  • 1
    @Otiel Lol in that case any thing can change, what if they change Main(string[] args) rule to Start(string[] args) ?? I am sure that will never happen, and so far and their best practice document says they never intent to change any API in its name or its behavior. But instead its extension is changed always. – Zenwalker Oct 24 '11 at 08:15
  • 1
    I'm not sure I get your point. I disagree with you when you say *its best to use String.Empty*. `""` and `String.Empty` will always stay that way. OP should use the one he finds the more readable, that's all. – Otiel Oct 24 '11 at 08:18
  • Well i am talking about best practices recommended by most developers, as i said its not a mandatory,so its upto you still! – Zenwalker Oct 24 '11 at 08:21
  • *'That day, Microsoft will be very dumb'* – on reading that can't contain myself, but didn't they prove to be already for long (even at the time of the post, much worse since, though)? – Aconcagua May 22 '23 at 14:27
-1

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().

Kissaki
  • 8,810
  • 5
  • 40
  • 42