問題描述
最近工作的同事告訴我在設(shè)置字符串變量時不要使用string.Empty
,而是使用null
,因為它會污染堆棧?
Recently a colleague at work told me not to use string.Empty
when setting a string variable but use null
as it pollutes the stack?
他說不要做
string myString=string.Empty;
但是做 string mystring=null;
這真的很重要嗎?我知道 string 是一個對象,所以它有點道理.
Does it really matter? I know string is an object so it sort of makes sense.
我知道這是一個愚蠢的問題,但您的觀點是什么?
I know is a silly question but what is your view?
推薦答案
null
和 Empty
差別很大,不建議隨意切換.但兩者都沒有任何額外的成本",因為 Empty
是一個單一的固定引用(您可以多次使用它).
null
and Empty
are very different, and I don't suggest arbitrarily switching between them. But neither has any extra "cost", since Empty
is a single fixed reference (you can use it any number of times).
堆棧上沒有由 ldsfld - 這種擔憂是......瘋狂.加載 null
可以說是稍微更便宜,但如果您不小心檢查值,可能會導致空引用異常.
There is no "pollution" on the stack caused by a ldsfld - that concern is.... crazy. Loading a null
is arguably marginally cheaper, but could cause null-reference exceptions if you aren't careful about checking the value.
就我個人而言,我兩者都不使用...如果我想要一個空字符串,我使用 ""
- 簡單明了.實習意味著這也沒有每次使用的開銷.
Personally, I use neither... If I want an empty string I use ""
- simple and obvious. Interning means this also has no per-usage overhead.
在 IL 級別,"" 和 Empty 之間的區(qū)別只是 ldstr 與 ldsfld - 但兩者都給出了相同的單個內(nèi)部字符串引用.此外,在最近的 .NET 版本中,JIT 直接攔截了這些,產(chǎn)生空字符串引用實際上沒有進行靜態(tài)字段查找.基本上,除了可讀性之外,完全沒有理由關(guān)心任何一種方式.我只用".
At the IL level, the difference here between "" and Empty is just ldstr vs ldsfld - but both give the same single interned string reference. Furthermore, in more recent .NET versions the JIT has direct interception of these, yielding the empty string reference without actually doing a static field lookup. Basically, there is exactly no reason to care either way, except readability. I just use "".
這篇關(guān)于string.Empty vs null.你使用哪個?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!