的String.Empty VS null.Which一个你使用?Empty、String、VS、Which

2023-09-02 21:51:36 作者:甜心萝莉酱✔

最近,一个同事在工作中告诉我,不要使用的String.Empty 设置一个字符串变量,但使用的时候因为它污染栈?

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?

他说,不这样做

字符串MyString的=的String.Empty; 但做串了mystring = NULL;

是否真的重要?我知道字符串是一个对象类,所以这是有道理的。

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 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 - 这种担心是....疯了。加载可以说是 略的便宜,但可能会导致空引用异常,如果你不小心检查值

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层面,这里的与空的区别仅仅是ldstr VS ldsfld - 但都给予同样的单串实习参考。此外,在最近的.NET版本的JIT有直接拦截了这些,产生空字符串引用的没有的实际做一个静态字段查找。基本上,恰好有没有理由去关心任何一种方式,除了可读性。我只是用。

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 "".