String.Empty 和 "" 和 null

不知不覺何時起,開始傾向於在代碼中使用String.Empty。今天決定來探究一下

 

 

  
http://www.cnblogs.com/SAL2928/archive/2007/07/16/820437.html
 
string.Empty不分配存儲空間
  ""分配一個長度爲空的存儲空間  
  所以一般用string.Empty

爲了以後跨平臺,還是用string.empty

在 C# 中,大多數情況下 "" 和 string.Empty 可以互換使用。比如:

string s = "";
string s2 = string.Empty;

if (s == string.Empty) {
  
// 
}
if語句成立


判定爲空字符串的幾種寫法,按照性能從高到低的順序是:

s.Length == 0  優於 s == string.Empty  優於 s == "" 


您關於String.Empty和Null的問題是這樣的,這兩個都是表示空字符串,其中有一個重點是string str1= String.Empty和 string str2=null 的區別,這樣定義後,str1是一個空字符串,空字符串是一個特殊的字符串,只不過這個字符串的值爲空,在內存中是有準確的指向的,string str2=null,這樣定義後,只是定義了一個string 類的引用,str2並沒有指向任何地方,在使用前如果不實例化的話,都將報錯。textBox1.Text的值爲零長度字符串 ""。

 

 

 

http://codebetter.com/blogs/brendan.tompkins/archive/2003/10/14/2585.aspx

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.

 
 
 

 

 

String.Empty vs ""

As David implies, there difference between String.Empty and “” are pretty small, but there is a difference.  “” actually creates an object, it will likely be pulled out of the string intern pool, but still… while String.Empty creates no object… so if you are really looking for ultimately in memory efficiency, I suggest String.Empty.  However, you should keep in mind the difference is so trival you will like never see it in your code…

 

As for System.String.Empty or string.Empty or String.Empty… my care level is low ;-)

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章