String.Empty vs “”


style="FONT-SIZE: 10pt; FONT-FAMILY: Arial">As st1 ns = "urn:schemas:contacts" /> style="FONT-SIZE: 10pt; FONT-FAMILY: Arial">David style="FONT-SIZE: 10pt; FONT-FAMILY: Arial"> href="http://dotnetweblogs.com/Dstone/posts/5901.aspx">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 code… "urn:schemas-microsoft-com:office:office" />


style="FONT-SIZE: 10pt; FONT-FAMILY: Arial"> 


style="FONT-SIZE: 10pt; FONT-FAMILY: Arial">As for System.String.Empty or
string.Empty or String.Empty… my care level is low ;-)


 

Comments (17)

  1. Where does String.Length == 0 stands in terms of memory efficiency compared to these two methods? Any ideas.

  2. al says:

    Can’t the compiler optimise "
    x == string.Empty or
    x == ""

    into x.Length == 0?

  3. Brian Grunkemeyer says:

    There are two reasons why looking at the length of the string is faster.

    1) Accessing static variables in appdomain-neutral assemblies in ngen’ed images involves going through one more level of indirection. So you dereference an extra pointer. (This may be fixed in a future version like v2.0 – you’d have to talk to one of our two ngen experts.)

    2) Since we have overloaded operator == on String, this is a method call. Calling Object.ReferenceEquals(x, String.Empty) would be a bit faster, but still suffers from #1.

    Yes, a language compiler or our JIT could theoretically optimize this. I don’t know of any that do. It seems like a bit of a corner case. But feel free to talk to your compiler vendors about this.

  4. Thong Nguyen says:

    "" is a constant. Try Console.WriteLine("" == String.Empty). I think you’ll find the JIT optimises the "" into String.Empty as there is no point in constructing a new object for a constant.

    The difference between using String.Length and doing a compare to "" is negligible (and often nonexistant) so there’s no point in worrying about it.

  5. Natalia says:

    Just a quick question to satify my personal curiosity… What is the difference between calling String.Empty vs. string.Empty. I know that the end-result is the same, but I am curious to see what’s happening internally. Does string.Empty actually call String.Empty internally?

    Thanks,

    Natalia

  6. Brad Abrams says:

    There is no difference between String and string… C# uses string as an alias for "String".

  7. De gustibus non est disputandum. – A Latin proverb, roughly "don't argue about matters of taste"

  8. SK says:

    不知不觉何时起,开始倾向于在代码中使用String.Empty。今天决定来探究一下