gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:43:30 28 4
gpt4 key购买 nike

我有这样一种情况,我会遇到很多重复的字符串,这些字符串会在内存中保存很长时间。我想使用 String.Intern 但我不想侵入任何潜在的应用程序资源,因为我的项目是一个库。这是如何工作的?

最佳答案

字符串的内部表是CLR-scoped :

First, the memory allocated for interned String objects is not likely be released until the common language runtime (CLR) terminates. The reason is that the CLR's reference to the interned String object can persist after your application, or even your application domain, terminates.

所以不仅实习生表不是程序集特定的,而且它可以比你的程序集活得更久。好消息是重复的字符串不会成为问题,因为相同的文字字符串一旦被驻留就会存在相同的引用。所以建议使用 Interning:

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

关于c# - .NET 是否为每个程序集创建一个字符串实习生池?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26544748/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com