简体   繁体   English

.NET是否为每个程序集创建一个字符串实习池?

[英]Does .NET create a string intern pool for each assembly?

I have a situation where I will encounter lots of duplicate strings which will persist in memory for a long time. 我有一种情况,我会遇到很多重复的字符串,这些字符串会在内存中持续很长时间。 I want to use String.Intern but I don't want to invade any potential application resources since my project is a library. 我想使用String.Intern但我不想入侵任何潜在的应用程序资源,因为我的项目是一个库。 How does this work? 这是如何运作的?

The intern table for strings is CLR-scoped : CLR-scoped的字符串实习表:

First, the memory allocated for interned String objects is not likely be released until the common language runtime (CLR) terminates. 首先,在公共语言运行时(CLR)终止之前,不太可能释放为被占用的String对象分配的内存。 The reason is that the CLR's reference to the interned String object can persist after your application, or even your application domain, terminates. 原因是CLR对interned String对象的引用可以在应用程序甚至应用程序域终止后继续存在。

So not only the intern table is not assembly-specific, but it can outlive your assembly. 因此,不仅实习表不是特定于装配的,而且它可以比您的装配寿命更长。 The good news is that duplicated strings won't be a problem since same literal strings exist with the same reference once interned. 好消息是重复的字符串不会成为问题,因为相同的文字字符串一旦被实现就存在相同的引用。 So Intern ing is recommended: 所以建议Intern

The common language runtime conserves string storage by maintaining a table, called the intern pool, that contains a single reference to each unique literal string declared or created programmatically in your program. 公共语言运行库通过维护一个名为intern pool的表来保存字符串存储,该表包含对在程序中以编程方式声明或创建的每个唯一文字字符串的单个引用。 Consequently, an instance of a literal string with a particular value only exists once in the system. 因此,具有特定值的文字字符串实例仅在系统中存在一次。

string s1 = "MyTest"; 
string s2 = new StringBuilder().Append("My").Append("Test").ToString(); 
string s3 = String.Intern(s2); 
Console.WriteLine((Object)s2==(Object)s1); // Different references.
Console.WriteLine((Object)s3==(Object)s1); // The same reference.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM