Reputation: 81262
I am certain that string.Empty is more efficient than using "" in .Net languages. What I would like to know is WHY is it more efficient?
Upvotes: 2
Views: 1164
Reputation: 29243
First of all, I'm not sure that it is more efficient. A reason it is a static is, it is basically a constant: there is only one empty string.
A more important issue is that there are some inconsistencies with string interning in .NET, which can result in comparisons with String.empty not always returning the expected result, depending on what version of the runtime you're using. Eric Lippert has written a fascinating blog post about it here.
(Example taken from Eric's post)
object obj = "";
string str1 = "";
string str2 = String.Empty;
Console.WriteLine(obj == str1); // true
Console.WriteLine(str1 == str2); // true
Console.WriteLine(obj == str2); // sometimes true, sometimes false?!
Upvotes: 6
Reputation: 158309
I think in most cases there is no difference. In normal cases, when you use ""
in your code this string will be interned and the same string instance will be reused. So there will not be more string instances around when using ""
as compared to String.Empty
.
If you want proof:
Dim a As String
Dim b As String
a = ""
b = ""
Console.WriteLine(Object.ReferenceEquals(a, b)) ' Prints True '
The above code prints True
also if you replace one of them with String.Empty
, so you can even mix the approaches without creating extra string instances.
Bottom line: the difference is personal taste.
Upvotes: 13
Reputation: 50273
""
will create an instance of an empty string in your application. Sure, .NET interns the string constants, but still, you will create one instance. String.Empty
, on the other hand, does not create any instance.
Upvotes: 2
Reputation: 8815
string.Empty is a singleton static const string that has been constructed, but "" will create a new string that is empty.
Upvotes: 0
Reputation: 187030
I don't think there is any performance gain in using string.Empty over "".
Its just a matter of personal preference.
Upvotes: 2