为什么默认情况下只有文字字符串保存在实习池中?
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
这篇关于为什么默认情况下只保存在实习生池中的文字字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!