Labels

Friday, May 23, 2008

String.Empty vs ""

String.Empty vs "":

string str = String.Empty; // Faster

string str = “”;

The fact - String.Empty is faster than “”.

Reason - This is because an object instance is created for empty quotes leading to more assembly code on the execution stack where String.Empty is a static constant and thus does not create an object instance, it's initial value is used instead.

So if you are really looking for ultimately in memory efficiency, I suggest String.Empty.


Gotcha:

string str = String.Empty;
Console.WriteLine(str);

Now an object is not created for str since it is initialized using String.Empty.
So what happens when the compiler executes the second line( Console.WriteLine(str)). If an object is not created this statement should have thrown an error.

Reference: http://www.csharper.net/blog/string_empty_vs_empty_quotes___quot__quot___vs_string_length.aspx

Thanks & Regards,

Arun Manglick || Senior Tech

No comments:

Post a Comment