.net String.Empty 和 ""(空字符串)有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/151472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between String.Empty and "" (empty string)?
提问by johnc
In .NET, what is the difference between String.Emptyand "", and are they interchangable, or is there some underlying reference or Localization issues around equality that String.Emptywill ensure are not a problem?
在 .NET 中,String.Empty和之间有什么区别"",它们是否可以互换,或者是否存在一些围绕平等的潜在参考或本地化问题,String.Empty以确保不是问题?
回答by Brian R. Bondy
In .NET prior to version 2.0, ""creates an object while string.Emptycreates no objectref, which makes string.Emptymore efficient.
在 .NET 2.0 之前的版本中,""创建一个对象而不string.Empty创建对象ref,这样string.Empty效率更高。
In version 2.0 and later of .NET, all occurrences of ""refer to the same string literal, which means ""is equivalent to .Empty, but still not as fast as .Length == 0.
在 .NET 2.0 及更高版本中,所有出现的""引用相同的字符串文字,这意味着""等价于.Empty,但仍然不如.Length == 0.
.Length == 0is the fastest option, but .Emptymakes for slightly cleaner code.
.Length == 0是最快的选择,但.Empty使代码更简洁。
回答by Habib
what is the difference between String.Empty and "", and are they interchangable
String.Empty 和 "" 之间有什么区别,它们是否可以互换
string.Emptyis a read-only field whereas ""is a compile time constant. Places where they behave differently are:
string.Empty是只读字段,而""是编译时常量。他们表现不同的地方是:
Default Parameter value in C# 4.0 or higher
C# 4.0 或更高版本中的默认参数值
void SomeMethod(int ID, string value = string.Empty)
// Error: Default parameter value for 'value' must be a compile-time constant
{
//... implementation
}
Case expression in switch statement
switch 语句中的 case 表达式
string str = "";
switch(str)
{
case string.Empty: // Error: A constant value is expected.
break;
case "":
break;
}
Attribute arguments
属性参数
[Example(String.Empty)]
// Error: An attribute argument must be a constant expression, typeof expression
// or array creation expression of an attribute parameter type
回答by chadmyers
The previous answers were correct for .NET 1.1 (look at the date of the post they linked: 2003). As of .NET 2.0 and later, there is essentially no difference. The JIT will end up referencing the same object on the heap anyhow.
之前的答案对于 .NET 1.1 是正确的(查看他们链接的帖子的日期:2003)。从 .NET 2.0 及更高版本开始,基本上没有区别。无论如何,JIT 最终将引用堆上的同一个对象。
According to the C# specification, section 2.4.4.5: http://msdn.microsoft.com/en-us/library/aa691090(VS.71).aspx
根据 C# 规范,第 2.4.4.5 节:http: //msdn.microsoft.com/en-us/library/aa691090(VS.71) .aspx
Each string literal does not necessarily result in a new string instance. When two or more string literals that are equivalent according to the string equality operator (Section 7.9.7) appear in the same assembly, these string literals refer to the same string instance.
每个字符串文字不一定会产生一个新的字符串实例。当两个或多个根据字符串相等运算符(第 7.9.7 节)等效的字符串文字出现在同一个程序集中时,这些字符串文字引用同一个字符串实例。
Someone even mentions this in the comments of Brad Abram's post
有人甚至在 Brad Abram 的帖子的评论中提到了这一点
In summary, the practical result of "" vs. String.Empty is nil. The JIT will figure it out in the end.
综上所述,"" vs. String.Empty 的实际结果为零。JIT 最终会解决这个问题。
I have found, personally, that the JIT is way smarter than me and so I try not to get too clever with micro-compiler optimizations like that. The JIT will unfold for() loops, remove redundant code, inline methods, etc better and at more appropriate times than either I or the C# compiler could ever anticipate before hand. Let the JIT do its job :)
我个人发现 JIT 比我聪明得多,所以我尽量不要让像这样的微编译器优化太聪明。JIT 将展开 for() 循环、删除冗余代码、内联方法等,并且在比我或 C# 编译器事先预期的更合适的时间。让 JIT 完成它的工作:)
回答by James Newton-King
String.Emptyis a readonlyfield while ""is a const. This means you can't use String.Emptyin a switch statement because it is not a constant.
String.Empty是只读字段,""而是const。这意味着您不能String.Empty在 switch 语句中使用,因为它不是常量。
回答by Bruno Martinez
Another difference is that String.Empty generates larger CIL code. While the code for referencing "" and String.Empty is the same length, the compiler doesn't optimize string concatenation (see Eric Lippert's blog post) for String.Empty arguments. The following equivalent functions
另一个区别是 String.Empty 会生成更大的 CIL 代码。虽然引用 "" 和 String.Empty 的代码长度相同,但编译器不会优化String.Empty 参数的字符串连接(请参阅 Eric Lippert 的博客文章)。以下等效函数
string foo()
{
return "foo" + "";
}
string bar()
{
return "bar" + string.Empty;
}
generate this IL
生成这个 IL
.method private hidebysig instance string foo() cil managed
{
.maxstack 8
L_0000: ldstr "foo"
L_0005: ret
}
.method private hidebysig instance string bar() cil managed
{
.maxstack 8
L_0000: ldstr "bar"
L_0005: ldsfld string [mscorlib]System.String::Empty
L_000a: call string [mscorlib]System.String::Concat(string, string)
L_000f: ret
}
回答by Eugene Katz
The above answers are technically correct, but what you may really want to use, for best code readability and least chance of an exception is String.IsNullOrEmpty(s)
上面的答案在技术上是正确的,但是为了获得最佳代码可读性和最小的异常机会,您可能真正想要使用的是String.IsNullOrEmpty(s)
回答by The_Lone_Devil
I tend to use String.Emptyrather than ""for one simple, yet not obvious reason:
"????????????????????"and ""are NOT the same, the first one actually has 16 zero width characters in it. Obviously no competent developer is going to put and zero width characters into their code, but if they do get in there, it can be a maintenance nightmare.
我倾向于使用String.Empty而不是""出于一个简单但不明显的原因:
"????????????????????"并且""不一样,第一个实际上有 16 个零宽度字符。显然,没有称职的开发人员会将零宽度字符放入他们的代码中,但如果他们真的进入了那里,这可能是维护的噩梦。
Notes:
笔记:
I used U+FEFFin this example.
Not sure if SO is going to eat those characters, but try it yourself with one of the many zero-width characters
I only came upon this thanks to https://codegolf.stackexchange.com/
我在这个例子中使用了U+FEFF。
不确定 SO 是否会吃掉这些字符,但请自己尝试使用许多零宽度字符之一
感谢https://codegolf.stackexchange.com/,我才发现了这一点
回答by Mojtaba Rezaeian
Use String.Emptyrather than "".
使用String.Empty而不是"".
This is more for speed than memory usage but it is a useful tip. The
""is a literal so will act as a literal: on the first use it is created and for the following uses its reference is returned. Only one instance of""will be stored in memory no matter how many times we use it! I don't see any memory penalties here. The problem is that each time the""is used, a comparing loop is executed to check if the""is already in the intern pool.On the other side,String.Emptyis a reference to a""stored in the .NET Framework memory zone.String.Emptyis pointing to same memory address for VB.NET and C# applications. So why search for a reference each time you need""when you have that reference inString.Empty?
这更多是为了速度而不是内存使用,但它是一个有用的技巧。这
""是一个文字,因此将充当文字:在第一次使用时创建它,并在以下使用中返回其引用。""无论我们使用多少次,都只会在内存中存储一个实例!我在这里没有看到任何内存损失。问题是每次""使用 时,都会执行一个比较循环来检查 是否""已经在实习池中。另一方面,String.Empty是对""存储在.NET Framework 内存区域中的的引用。String.Empty指向 VB.NET 和 C# 应用程序的相同内存地址。那么为什么每次需要""时都搜索参考文献String.Empty?
Reference: String.Emptyvs ""
回答by Jason Hymanson
All instances of "" are the same, interned string literal (or they should be). So you really won't be throwing a new object on the heap every time you use "" but just creating a reference to the same, interned object. Having said that, I prefer string.Empty. I think it makes code more readable.
"" 的所有实例都是相同的,内部字符串文字(或者它们应该是)。所以你真的不会在每次使用 "" 时在堆上抛出一个新对象,而只是创建对同一个内部对象的引用。话虽如此,我更喜欢 string.Empty。我认为它使代码更具可读性。

