String.Empty vs. ""
So, I just converted a bunch of code that used "" as an empty string like this:if(myString == "") anotherString = "";
to
if(myString.Equals(String.Empty)) anotherString = String.Empty;
and I'm wondering if I did the right thing, using String.Empty. I hate having quoted strings in code and prefer to stay away from them whenever possible. This generally leads to code that is more strongly typed, and easier to maintain, so using String.Empty intuitively feels better than ““. But, I've actually found a concrete reason to use String.Empty - I did some research and found that in a test, str.Equals(String.Empty) is faster than comparing to ""! Well, okay. Research isn't the right word, “Doing one google search and accepting on faith the first post I saw” is slightly more accurate. I even created a little graph of the claims in this post here, that String.Empty is faster. I'm too lazy to do the test myself, so if you want to verify this, knock yourself out. I do love making graphs though.
----------------------------------------------------------------------------------
Here are the results
Checking with [s == ""] test.
Empty string, 10315.6250 milliseconds
Short string, 8307.8125 milliseconds
Long string, 8564.0625 milliseconds
Checking with [s == string.Empty] test.
Empty string, 3573.4375 milliseconds
Short string, 8307.8125 milliseconds
Long string, 8603.1250 milliseconds
Checking with [s.Equals("")] test.
Empty string, 9517.1875 milliseconds
Short string, 7537.5000 milliseconds
Long string, 7576.5625 milliseconds
Checking with [s.Equals(string.Empty)] test.
Empty string, 9540.6250 milliseconds
Short string, 7515.6250 milliseconds
Long string, 7607.8125 milliseconds
Checking with [s.Length == 0] test.
Empty string, 443.7500 milliseconds
Short string, 443.7500 milliseconds
Long string, 445.3125 milliseconds
http://
----------------------------------------------------------------------------------
String.IsNullOrEmpty()
--------------------------------
NULL = 62 milliseconds
Empty = 46 milliseconds
"" = 46 milliseconds
str == null
---------------
NULL = 31 milliseconds
Empty = 46 milliseconds
"" = 31 milliseconds
str == null || str == String.Empty
----------------------------------------------
NULL = 46 milliseconds
Empty = 62 milliseconds
"" = 359 milliseconds
str == null || str == ""
------------------------------
NULL = 46 milliseconds
Empty = 343 milliseconds
"" = 78 milliseconds
str == null || str.length == 0
---------------------------------------
NULL = 31 milliseconds
Empty = 63 milliseconds
"" = 62 milliseconds
http://
[[it] 本帖最后由 live41 于 2008-2-5 05:10 编辑 [/it]]