在。net中,String和。net之间的区别是什么?空和"",他们是可交换的,或者有一些潜在的引用或本地化问题,围绕相等的字符串。空将保证都不是问题?


当前回答

使用字符串。空而不是""。

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.Empty is a reference to a "" stored in the .NET Framework memory zone. String.Empty is 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 in String.Empty?

参考:字符串。Empty和""

其他回答

在2.0版本之前的。net中,""创建一个对象while字符串。Empty不会创建objectref,它会生成string。放空更有效率。

在。net 2.0及以后版本中,所有出现的""都指向相同的字符串字面值,这意味着""相当于. empty,但仍然不如. length == 0快。

. length == 0是最快的选项,但是. empty会使代码更简洁。

有关更多信息,请参阅. net规范。

这都不重要!

以前的一些讨论:

http://www.codinghorror.com/blog/archives/000185.html

http://blogs.msdn.com/brada/archive/2003/04/22/49997.aspx

http://blogs.msdn.com/brada/archive/2003/04/27/50014.aspx

使用字符串。空而不是""。

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.Empty is a reference to a "" stored in the .NET Framework memory zone. String.Empty is 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 in String.Empty?

参考:字符串。Empty和""

string mystring = "";
ldstr ""

LDSTR将一个新的对象引用推入存储在元数据中的字符串字面值。

string mystring = String.Empty;
ldsfld string [mscorlib]System.String::Empty

LDSFLD将静态字段的值推入计算堆栈

我倾向于使用String。用空代替"",因为在我看来,这样更清晰,也不那么vb。

字符串。Empty不创建对象,而""创建对象。然而,正如这里所指出的,差异是微不足道的。