公共语言运行时通过维护名为拘留池的表来节省字符串存储,该表包含对程序中以编程方式声明或创建的每个唯一文本字符串的单个引用。 因此,系统中仅存在一个具有特定值的文本字符串的实例。
string.Intern 是终生制的,一旦加入只要程序不重启,就会一直存在。
// Sample for String.Intern(String) using System; using System.Text; class Sample { public static void Main() { string s1 = "MyTest"; string s2 = new StringBuilder().Append("My").Append("Test").ToString(); string s3 = String.Intern(s2); Console.WriteLine($"Is s2 the same reference as s1?: {(Object)s2 == (Object)s1}"); Console.WriteLine($"Is s3 the same reference as s1?: {(Object)s3 == (Object)s1}"); } } /* This example produces the following results: Is s2 the same reference as s1?: False Is s3 the same reference as s1?: True */
Microsoft.Toolkit.HighPerformance 包中StringPool类解决重复字符串实例过多,导致浪费内存的情况。优点是可以释放