在。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和""

其他回答

string mystring = "";
ldstr ""

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

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

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

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

前面的答案对于。net 1.1是正确的(查看他们链接的帖子的日期:2003年)。至于. net 2.0和以后的版本,基本上没有区别。无论如何,JIT最终都会引用堆上相同的对象。

根据c#规范,第2.4.4.5节: http://msdn.microsoft.com/en-us/library/aa691090 (VS.71) . aspx

每个字符串字面值不一定会产生一个新的字符串实例。当两个或多个根据字符串相等运算符(第7.9.7节)等效的字符串字面值出现在同一个程序集中时,这些字符串字面值引用同一个字符串实例。

有人甚至在布拉德·亚伯拉姆的帖子评论中提到了这一点

总之,"" vs. String的实际结果。Empty是nil。JIT最终会弄清楚的。

就我个人而言,我发现JIT比我聪明得多,所以我尽量在微编译器优化方面不太聪明。JIT将展开for()循环,删除冗余代码,内联方法等,在比我或c#编译器之前预期的更好和更合适的时间。让JIT来做它的工作吧:)

当您在视觉上扫描代码时,""会像字符串一样呈现彩色。字符串。Empty看起来像常规的类成员访问。在快速浏览的过程中,更容易发现“”或凭直觉理解其含义。

找出字符串(堆栈溢出着色不是很有帮助,但在VS中这是更明显的):

var i = 30;
var f = Math.Pi;
var s = "";
var d = 22.2m;
var t = "I am some text";
var e = string.Empty;

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

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

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

有关更多信息,请参阅. 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和""