c# - 为什么默认情况下只有文字字符串保存在实习生池中?

标签 c# .net string compiler-construction clr

为什么默认情况下只有文字字符串保存在实习生池中?

示例来自 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/

相关文章:

c# - 如何在 asp.net MVC 的 HTML 帮助程序中将 Razor 与字符串文字混合

c# - 用于更新操作的 CreatedAtAction 模拟

.net - C# .Net 双问题... 6.8 != 6.8?

c# - 将字符串数组转换为小写

c# - LINQ 从 4 个 IEnumerable 列表中选择不同的

c# - 为什么无法覆盖 getter-only 属性并添加 setter?

.net - 为什么 Guid.NewGuid 总是在完全相同的位置有一个 4?

python - 尝试根据大小写将一个字符串解析为两个单独的字符串

regex - Delphi - 如何从字符串中提取数字?

c# - LINQ 中的返回模态平均值(模式)