string.Empty vs null.Which one do you use?(string.Empty vs null.你使用哪个?)
问题描述
最近工作的同事告诉我在设置字符串变量时不要使用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 之间的区别只是 ldstr 与 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 "".
这篇关于string.Empty vs null.你使用哪个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:string.Empty vs null.你使用哪个?
基础教程推荐
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
