String.Empty versus “”
Possible Duplicate:
What is the difference between String.Empty and “”
据Brad Abrams称:
As David implies, there difference
between String.Empty and"" are pretty
small, but there is a difference. ""
actually creates an object, it will
likely be pulled out of the string
intern pool, but still… while
String.Empty creates no object… so if
you are really looking for ultimately
in memory efficiency, I suggest
String.Empty. However, you should
keep in mind the difference is so
trival you will like never see it in
your code...As for System.String.Empty or
string.Empty or String.Empty… my care
level is low ;-)
更新(2015年6月3日):
评论中提到,上述2003年的引用不再真实(我假设这是指
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class Program { static void Main() { // Outputs"True" Debug.WriteLine(string.IsInterned(string.Empty) != null); } } class Program { static void Main() { // Outputs"True" Debug.WriteLine(string.IsInterned("") != null); } } |
这表明,当代码开始运行时,
布拉德评论中最重要的部分是:
you should keep in mind the difference is so trival you will
like never see it in your code...
这就是底线。在"和string.empty之间进行选择不是基于性能的决定。不要浪费很多时间去想它。根据您发现更具可读性的内容或项目中已经使用的约定进行选择。
没什么不同。
http://msdn.microsoft.com/en-us/library/system.string.empty.aspx:
The value of this field is the zero-length string,"".
In application code, this field is most commonly used in assignments to initialize a string variable to an empty string. To test whether the value of a string is String.Empty, use the IsNullOrEmpty method.
不过,在大多数情况下,我发现使用
没有区别。有些人喜欢使用
string.empty始终是同一个对象
"始终是一个新对象,垃圾收集器可能必须删除它。
因此,应始终使用string.empty而不是"。
1 2 | string a=""; string b=string.Empty; |
翻译为
1 2 | IL_0000: ldstr "" IL_0005: ldsfld System.String.Empty |