Today I will talk about strings, and more particularly about empty strings (or if you prefer string containing zero characters).
#First question: What is the difference between
Since the .NET 2.0, there is no difference. The proof:
string s1 = ""; string s2 = string.Empty; Console.WriteLine(ReferenceEquals(s1, s2)); //true
With .NET 1.1, the difference is at the allocation level.
"" creates a string while
string.Empty using the pre-created string.
#Second question: How to test if a string is empty?
There are four ways to do this:
- Equality test:
str == ""or
str == string.Empty
- Reference test
- Test on the length:
str.Length == 0
- Using the function:
String.IsNullOrEmpty(str)(not exactly the same as it also check
To know what is the quickest way, I did a little test. For this test I used two strings:
string s1 = string.Empty; string s2 = "foobar";
Here is a table with all the results. The times displayed are in seconds, and are calculated for 2147483647 (
|s1 (x86)||s2 (x86)||s1 (x64)||s2 (x64)|
|str == string.Empty||11782||18698||15012||18200|
|Length == 0||13902||14306||9604||9676|
As can be seen the difference is minimal and depends on the intended architecture. Unless one million comparisons are made, all methods are equivalents. So choose the one you find the most readable.
Do you have a question or a suggestion about this post? Contact me!