为什么默认情况下只有文字字符串保存在实习生池中?
示例来自 MSDN :
String s1 = "MyTest";
String s2 = new StringBuilder().Append("My").Append("Test").ToString();
String s3 = String.Intern(s2);
Console.WriteLine("s1 == '{0}'", s1);
Console.WriteLine("s2 == '{0}'", s2);
Console.WriteLine("s3 == '{0}'", s3);
Console.WriteLine("Is s2 the same reference as s1?: {0}", (Object)s2==(Object)s1);
Console.WriteLine("Is s3 the same reference as s1?: {0}", (Object)s3==(Object)s1);
/*
This example produces the following results:
s1 == 'MyTest'
s2 == 'MyTest'
s3 == 'MyTest'
Is s2 the same reference as s1?: False
Is s3 the same reference as s1?: True
*/
最佳答案
简短的回答:驻留文字字符串在运行时便宜并且节省内存。驻留非文字字符串在运行时开销很大,因此节省了少量内存以换取使常见情况变慢。
interning-strings-at-runtime“优化”的成本并没有带来好处,因此实际上并不是优化。驻留文字字符串的成本很低,因此确实为 yield 付出了代价。
我在这里更详细地回答你的问题:
http://blogs.msdn.com/b/ericlippert/archive/2009/09/28/string-interning-and-string-empty.aspx
关于c# - 为什么默认情况下只有文字字符串保存在实习生池中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8509035/