Wednesday, March 28, 2012

String.Empty or ""

What's better, and why?

string myString = "";

or

string myString = String.Empty;


ThanksString.Empty
"" will be converted into String.Empty behind the scenes ... that means a little bit extra overhead
string myString = "";

is faster than

string myString = String.Empty;

String.Empty
will create a new String object, and set it to an empty string. The mystring variable will reference this new object in memory. Where if you use "" the variable mystring will just reference an already empty string in memory. It will not explicitly create a new empty string object.

Did that make sense? Bottom line there is more overhead to use

String.Empty

Chris Gastin
String.Empty is a static constant (readonly), immutable string reference in memory. Whenever you use it, it is shared across the board (and actually isdefined as ""). So, making a bunch of strings point to this reference in memory will have only the overhead of creating more pointers, but not more objects. There is only ONE String.Empty.

All strings are immutable and saying setting 5 strings equal to the same thing results in no extra overhead:

string one = "x";
string two = "x";
string three = "x";
They all point to the same memory location because the compiler knows ahead of time, assuming the values are constant, that they are the same and memory should not be wasted. If you were to say
two += "y";
, then this would generate a NEW string object at that point for ONLY the two string, and change the pointer in memory (and this also happens to be exactly why the StringBuilder class is more efficient with concatenation).
Thanks for the replies ... So, is one "better" to use?

0 comments:

Post a Comment