locked
what is the difference between String.Empty and "" ? RRS feed

  • Question

  • Today was not a very good day. I received lot of review comments on my code wherein I have used "". Most of the comments say, I should use String.Empty but not "". The reason they gave was String.Empty performs well over "". But I don't think so.  I think both are same. I didn't argue because I was unsure about it. Later I googled and found that "" creates an object but String.Empty doesn't. But, how? I think that also was wrong answer because if I create a String like below, and hover mouse over str, it shows "" but not String.Empty.

    string str = string.Empty;   //intellisense shows str is ""
    

    But still I am unsure. So, please let me know what is the difference between String.Empty and "".
    Tuesday, December 20, 2011 3:57 PM

Answers

  • Don't worry. You are correct. There is no difference at all between String.Empty and "". Read this page for more info. But I also prefer String.Empty because it looks nice to me and is more readable. Also, a problem with "" is that sometimes by mistake it is written as " " which is not an empty string. However, it is just programmer's choice whether to use "" or String.Empty while the two are identical to each other.
    Please mark this post as answer if it solved your problem. Happy Programming!
    • Proposed as answer by Pantelis44999 Tuesday, December 20, 2011 4:13 PM
    • Marked as answer by Vidya Bhatt Wednesday, December 21, 2011 3:19 AM
    Tuesday, December 20, 2011 4:06 PM
  • @Advesh - So, you mean to say even performance wise there is no difference? I came across this artcle on msdn and according to it,  "" actually creates an object. What does that mean?


    No it doesn't create any object if I am not wrong. In fact, both "" and String.Empty make use of String Interning. For example,

    String first = String.Empty;
    String second  = "";
    
    bool bothReferSingleObject = Object.ReferenceEquals(first, second);   // --------------> This will be TRUE
    

     You see that Object.ReferenceEquals(first, second) returns TRUE which means both first and second refer same object. This also means "" doesn't create any seperate object.


    Please mark this post as answer if it solved your problem. Happy Programming!
    • Marked as answer by Vidya Bhatt Wednesday, December 21, 2011 3:20 AM
    Tuesday, December 20, 2011 4:44 PM
  • Hi Alex,

    I tested your code and guess what, the results are reverse. "" executes more faster than String.Empty !!!!!! I used the below code,

    String test;
    String result = String.Empty;
    int count = 1000000000;
    Stopwatch sw = Stopwatch.StartNew();
    for (int idx = 0; idx < count; ++idx)
    {
        test = "";
    }
    sw.Stop();
    result += "\"\"                      : " + sw.ElapsedMilliseconds.ToString() + "\n";
    
    sw.Reset();
    sw.Start();
    for (int idx = 0; idx < count; ++idx)
    {
        test = string.Empty;
    }
    sw.Stop();
                
    result += "String.Empty   : " + sw.ElapsedMilliseconds.ToString() + "\n";
    

    and the result is this,

    @Vidya - You should be much happier now.. In this case "" outperformed String.Empty :)

     


    Please mark this post as answer if it solved your problem. Happy Programming!
    • Marked as answer by Vidya Bhatt Wednesday, December 21, 2011 3:20 AM
    Tuesday, December 20, 2011 5:58 PM
  • The difference is minimal. Keeping in mind that a simple garbage collection run in either of the loops would offset the difference, as would any external influence, I would't go out on a difference of less than 20 ms on a million iterations.

    The IL used is different, yes, though loading a static field or looking up a string value from the String intern table (and in most cases the first item on the string intern table) shouldn't cause much of a difference.

    http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.ldstr.aspx

    http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.ldsfld.aspx

    I prefer to use string.Empty, as it's easier to read in my opinion. And you can probably say that Microsoft wouldn't have put the field in to the BCL if it didn't perform well.

     

    Results on my system with a pre-heat set of runs and full garbage collection between each test results in:

    A 2279
    B 2307
    A 2273
    B 2222
    A 2219
    B 2208
    A 2245
    B 2263

    As you can see, they're taking turns on the best performance.

    So for performance reasons, don't pick one or the other. For readability and safety in comparisons, pick string.Empty.

     


    My blog: blog.jessehouwing.nl
    • Marked as answer by Vidya Bhatt Wednesday, December 21, 2011 3:20 AM
    Tuesday, December 20, 2011 6:34 PM
  • Questions like this are total time wasters.  How long would it take to answer unequivocally by looking at the Reference Source?

    public static readonly String Empty = "";
    

     


    Ah, but that's not an apples to apples comparison.  String.Empty is a static field reference, while "" logically creates a new string object on the Gen0 heap.  The fact that the interned strings table negates this object creation in many cases is an optimization that makes these two cases much closer in performance than they otherwise would be.  From various tests that posters on this thread have run, the difference in performance is below the noise threshold of the test methodology - in other words, a meaningless difference.  Were it not for interning of string literals, the difference would no doubt be statistically significant.

    Within my own code, I prefer String.Empty because I think it more clearly documents the intention - a non-null, 0-length string, while empty quotes may be indicative of a literal that was overlooked: the programmer used "" intending to supply a value but then neglected to do so.  Many programming conventions, especially those focused on globalized code severely restrict the use of literal strings, so the use of String.Empty is more compatible with those conventions as well.

     

     


    -cd Mark the best replies as answers!
    • Marked as answer by Vidya Bhatt Wednesday, December 21, 2011 3:20 AM
    Tuesday, December 20, 2011 8:46 PM
  • Questions like this are total time wasters.  How long would it take to answer unequivocally by looking at the Reference Source?

     

    public static readonly String Empty = "";
    

     

    It does sound like a time waster. On the other hand, it sounds like they are technically not exactly the same thing, since one loads from a field and the other loads directly from the intern table.

    It seems like it goes without saying that all of this is meaningless in any real world usage, though. String.Empty and "" are equal for performance. But, performance is not the only factor. In most cases, performance is not even in the top 3 standards which should be used when evaluating a program or feature. First is usability, second is maintainability, third is profitability. Which one you use may not affect performance, but it does affect maintainability, which is even more important.

    Whenever you're trying to decide between two options, pick the one that is easier to understand and maintain. Don't worry about performance unless and until you have a specific performance issue to address. Premature optimization and over-exaggeration of performance importance is just a waste of money.


    Check out My Blog for tech news, development tips, and other information for geeks like me.
    • Marked as answer by Vidya Bhatt Wednesday, December 21, 2011 3:21 AM
    Tuesday, December 20, 2011 10:17 PM

All replies

  • Don't worry. You are correct. There is no difference at all between String.Empty and "". Read this page for more info. But I also prefer String.Empty because it looks nice to me and is more readable. Also, a problem with "" is that sometimes by mistake it is written as " " which is not an empty string. However, it is just programmer's choice whether to use "" or String.Empty while the two are identical to each other.
    Please mark this post as answer if it solved your problem. Happy Programming!
    • Proposed as answer by Pantelis44999 Tuesday, December 20, 2011 4:13 PM
    • Marked as answer by Vidya Bhatt Wednesday, December 21, 2011 3:19 AM
    Tuesday, December 20, 2011 4:06 PM
  • I'd guess that there is a performance difference between "" and String.Empty, but it's so small that you'll never observe it
    Tuesday, December 20, 2011 4:14 PM
  • @Advesh - So, you mean to say even performance wise there is no difference? I came across this artcle on msdn and according to it,  "" actually creates an object. What does that mean?

     

    @Samuel - Yeah. I found that too. But what performance difference ?


    • Edited by Vidya Bhatt Tuesday, December 20, 2011 4:22 PM
    Tuesday, December 20, 2011 4:21 PM
  • @Advesh - So, you mean to say even performance wise there is no difference? I came across this artcle on msdn and according to it,  "" actually creates an object. What does that mean?


    No it doesn't create any object if I am not wrong. In fact, both "" and String.Empty make use of String Interning. For example,

    String first = String.Empty;
    String second  = "";
    
    bool bothReferSingleObject = Object.ReferenceEquals(first, second);   // --------------> This will be TRUE
    

     You see that Object.ReferenceEquals(first, second) returns TRUE which means both first and second refer same object. This also means "" doesn't create any seperate object.


    Please mark this post as answer if it solved your problem. Happy Programming!
    • Marked as answer by Vidya Bhatt Wednesday, December 21, 2011 3:20 AM
    Tuesday, December 20, 2011 4:44 PM
  • It's not entirely true that "" and string.Empty are the same. There are conditions which can cause the creation of two different objects, where the object.Equals(string.Empty, "") is different than string.Equals(string.Empty, "").

    This is because though the contents are the same, the actual objects are different.

    See also: http://stackoverflow.com/questions/3678792/are-string-equals-and-operator-really-same


    My blog: blog.jessehouwing.nl
    Tuesday, December 20, 2011 4:46 PM
  • Hi Jesse, I just want to know, whether there is any performance gain in using System.Empty over "". Seeing Adavesh's comment I feel there is no difference. What do you say?
    Tuesday, December 20, 2011 5:26 PM
  • the MSIL between "" and String.Empty is different

    one is ldstr ""  and the other is ldsfld string [mscorlib]

    you can try the following code

    using  System.Diagnostics;
    static void Main(string[] args)
    {
        String test;
        int count=1000000000;
        Stopwatch sw = Stopwatch.StartNew();
        for (int idx = 0; idx < count; ++idx)
        {
            test = "";
        }
        sw.Stop();
        Console.WriteLine(sw.ElapsedMilliseconds.ToString());
    
        sw.Reset();
        sw.Start();
        for (int idx = 0; idx < count; ++idx)
        {
            test = string.Empty;
        }
        sw.Stop();
        Console.WriteLine(sw.ElapsedMilliseconds.ToString());
        Console.Read();
    }
    

    referenced from: http://www.dotblogs.com.tw/larrynung/archive/2009/12/22/12615.aspx


    以下為簽名檔,如果你愛拉椅子坐那就是你的問題。
    先查MSDN文件庫
    再用GOOGLE搜尋
    才到論壇來發問

    這是論壇不是技術支援中心
    沒有人得無償解答你的問題

    在標題或文章註明很急
    不會增加網友回覆速度
    Tuesday, December 20, 2011 5:27 PM
  • Both are equal..
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful". Happy Coding...
    Tuesday, December 20, 2011 5:49 PM
  • Hi Alex,

    I tested your code and guess what, the results are reverse. "" executes more faster than String.Empty !!!!!! I used the below code,

    String test;
    String result = String.Empty;
    int count = 1000000000;
    Stopwatch sw = Stopwatch.StartNew();
    for (int idx = 0; idx < count; ++idx)
    {
        test = "";
    }
    sw.Stop();
    result += "\"\"                      : " + sw.ElapsedMilliseconds.ToString() + "\n";
    
    sw.Reset();
    sw.Start();
    for (int idx = 0; idx < count; ++idx)
    {
        test = string.Empty;
    }
    sw.Stop();
                
    result += "String.Empty   : " + sw.ElapsedMilliseconds.ToString() + "\n";
    

    and the result is this,

    @Vidya - You should be much happier now.. In this case "" outperformed String.Empty :)

     


    Please mark this post as answer if it solved your problem. Happy Programming!
    • Marked as answer by Vidya Bhatt Wednesday, December 21, 2011 3:20 AM
    Tuesday, December 20, 2011 5:58 PM
  • Hi Vidya Bhatt,

                      Both the are equal but it both works different as per the location used.

    For Ex:

    in this below code the output will be "Not Empty String"

    and also while trim() the String test than only it becomes equal to string.empty

    that is    test.trim() = string.Empty.

     Dim test As String = " "
            If String.IsNullOrEmpty(test) Then
                MessageBox.Show("Empty String")
            Else
                MessageBox.Show("Not Emtpy String")
            End If
    


    If my answer solve your problem,Please click "Mark As Answer" on that post and "Mark as Helpful". Manikandan
    Tuesday, December 20, 2011 6:24 PM
  • The difference is minimal. Keeping in mind that a simple garbage collection run in either of the loops would offset the difference, as would any external influence, I would't go out on a difference of less than 20 ms on a million iterations.

    The IL used is different, yes, though loading a static field or looking up a string value from the String intern table (and in most cases the first item on the string intern table) shouldn't cause much of a difference.

    http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.ldstr.aspx

    http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.ldsfld.aspx

    I prefer to use string.Empty, as it's easier to read in my opinion. And you can probably say that Microsoft wouldn't have put the field in to the BCL if it didn't perform well.

     

    Results on my system with a pre-heat set of runs and full garbage collection between each test results in:

    A 2279
    B 2307
    A 2273
    B 2222
    A 2219
    B 2208
    A 2245
    B 2263

    As you can see, they're taking turns on the best performance.

    So for performance reasons, don't pick one or the other. For readability and safety in comparisons, pick string.Empty.

     


    My blog: blog.jessehouwing.nl
    • Marked as answer by Vidya Bhatt Wednesday, December 21, 2011 3:20 AM
    Tuesday, December 20, 2011 6:34 PM
  • Questions like this are total time wasters.  How long would it take to answer unequivocally by looking at the Reference Source?

    public static readonly String Empty = "";
    

    Tuesday, December 20, 2011 6:57 PM
  • @John, not completely; The Performance question is not really valid, but as far as comparison is concerned, there is an important difference every developer should know:

    http://blogs.msdn.com/b/ericlippert/archive/2009/09/28/string-interning-and-string-empty.aspx


    My blog: blog.jessehouwing.nl
    Tuesday, December 20, 2011 8:46 PM
  • Questions like this are total time wasters.  How long would it take to answer unequivocally by looking at the Reference Source?

    public static readonly String Empty = "";
    

     


    Ah, but that's not an apples to apples comparison.  String.Empty is a static field reference, while "" logically creates a new string object on the Gen0 heap.  The fact that the interned strings table negates this object creation in many cases is an optimization that makes these two cases much closer in performance than they otherwise would be.  From various tests that posters on this thread have run, the difference in performance is below the noise threshold of the test methodology - in other words, a meaningless difference.  Were it not for interning of string literals, the difference would no doubt be statistically significant.

    Within my own code, I prefer String.Empty because I think it more clearly documents the intention - a non-null, 0-length string, while empty quotes may be indicative of a literal that was overlooked: the programmer used "" intending to supply a value but then neglected to do so.  Many programming conventions, especially those focused on globalized code severely restrict the use of literal strings, so the use of String.Empty is more compatible with those conventions as well.

     

     


    -cd Mark the best replies as answers!
    • Marked as answer by Vidya Bhatt Wednesday, December 21, 2011 3:20 AM
    Tuesday, December 20, 2011 8:46 PM
  • Questions like this are total time wasters.  How long would it take to answer unequivocally by looking at the Reference Source?

     

    public static readonly String Empty = "";
    

     

    It does sound like a time waster. On the other hand, it sounds like they are technically not exactly the same thing, since one loads from a field and the other loads directly from the intern table.

    It seems like it goes without saying that all of this is meaningless in any real world usage, though. String.Empty and "" are equal for performance. But, performance is not the only factor. In most cases, performance is not even in the top 3 standards which should be used when evaluating a program or feature. First is usability, second is maintainability, third is profitability. Which one you use may not affect performance, but it does affect maintainability, which is even more important.

    Whenever you're trying to decide between two options, pick the one that is easier to understand and maintain. Don't worry about performance unless and until you have a specific performance issue to address. Premature optimization and over-exaggeration of performance importance is just a waste of money.


    Check out My Blog for tech news, development tips, and other information for geeks like me.
    • Marked as answer by Vidya Bhatt Wednesday, December 21, 2011 3:21 AM
    Tuesday, December 20, 2011 10:17 PM
  • Thank you everyone. The comments are really informative. May be this question is a time waster for .NET masters but now I can show this thread to my code reviewers that there is hardly any performance difference between "" & Empty. But, yeah, I understand now that String.Empty should be preferred as this has other benefits.

    Thanks again.

    Wednesday, December 21, 2011 3:03 AM
  • Don't worry. You are correct. There is no difference at all between String.Empty and "". Read this page for more info. But I also prefer String.Empty because it looks nice to me and is more readable. Also, a problem with "" is that sometimes by mistake it is written as " " which is not an empty string. However, it is just programmer's choice whether to use "" or String.Empty while the two are identical to each other.
    Please mark this post as answer if it solved your problem. Happy Programming!

    I think there is difference , though small.

    http://blogs.msdn.com/b/brada/archive/2003/04/22/49997.aspx

    Wednesday, December 21, 2011 8:22 AM
  • Just a comment I'd like to tack on since we're talking mostly about readability and maintainability.

    I find that not very many people tend to use the string.IsNullOrEmpty(str) method, and instead do an "if( string != string.Empty)" or "if(string != "")".  (With the null check and-ed in there if appropriate.)  I find that the IsNullOrEmpty method is not only quicker and easier to type, but it is also quicker and easier to read.

    Wednesday, December 21, 2011 9:10 PM