Why only literal strings saved in the intern pool by default?(为什么默认情况下只保存在实习生池中的文字字符串?)
问题描述
为什么默认情况下只有文字字符串保存在实习池中?
Why by default only literal strings are saved in the intern pool?
示例来自 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
*/
推荐答案
简短的回答:实习文字字符串在运行时很便宜并且节省内存.嵌入非文字字符串在运行时很昂贵,因此节省了少量内存,以换取使常见情况变慢.
The short answer: interning literal strings is cheap at runtime and saves memory. Interning non-literal strings is expensive at runtime and therefore saves a tiny amount of memory in exchange for making the common cases much slower.
interning-strings-at-runtime优化"的成本并没有带来收益,因此实际上并不是优化.实习文字字符串的成本很便宜,因此确实为收益付出了代价.
The cost of the interning-strings-at-runtime "optimization" does not pay for the benefit, and is therefore not actually an optimization. The cost of interning literal strings is cheap and therefore does pay for the benefit.
我在这里更详细地回答你的问题:
I answer your question in more detail here:
http://blogs.msdn.com/b/ericlippert/archive/2009/09/28/string-interning-and-string-empty.aspx
这篇关于为什么默认情况下只保存在实习生池中的文字字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么默认情况下只保存在实习生池中的文字字符串?
基础教程推荐
- C# 9 新特性——record的相关总结 2023-04-03
- 如果条件可以为空 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 将数据集转换为列表 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 从 C# 控制相机设备 2022-01-01
