为什么要保存在默认情况下,实习生池只包含文字字符串? [英] Why only literal strings saved in the intern pool by default?

查看:216
本文介绍了为什么要保存在默认情况下,实习生池只包含文字字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

MSDN 的例子:

 字符串S1 =MyTest的;
。字符串s2 =新的StringBuilder()追加(我)追加(测试)的ToString()。
串S3 =的String.intern(S2);
Console.WriteLine(S1 = ='{0}',S1);
Console.WriteLine(S2 = ='{0}',S2);
Console.WriteLine(S3 =='{0}',S3);
Console.WriteLine(为S2相同的参考为S1?:{0}(对象)S2 = =(对象)S1);
Console.WriteLine(是S3相同基准为S1?:{0}(对象)S3 ==(对象)S1);

/ *
该示例产生以下结果:
S1 =='MyTest的
S2 =='MyTest的
S3 =='MyTest的
为S2相同的附图为S1 ?:假
是S3相同的附图为S1?:真
* /
 

解决方案

简短的回答:实习文字字符串是的便宜,运行时节省内存的。实习非文字字符串是的贵在运行时的,因此节省内存微量换取使得在多数情况下慢得多的。

在实习弦,在运行时优化的成本不支付的利益,因此不是真正的优化。实习文字字符串的成本低廉,因此它支付的利益。

我的回答更详细的问题在这里:

<一个href="http://blogs.msdn.com/b/ericlippert/archive/2009/09/28/string-interning-and-string-empty.aspx">http://blogs.msdn.com/b/ericlippert/archive/2009/09/28/string-interning-and-string-empty.aspx

Why by default only literal strings are saved in the intern pool?

Example from 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.

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

这篇关于为什么要保存在默认情况下,实习生池只包含文字字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆