c# - CLR/JVM 是否为所有正在运行的 .net/java 应用程序保留一个实习生池?

标签 c# java .net string string-interning

以下摘自 MSDN:

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.

For example, if you assign the same literal string to several variables, the runtime retrieves the same reference to the literal string from the intern pool and assigns it to each variable.

The Intern method uses the intern pool to search for a string equal to the value of str. If such a string exists, its reference in the intern pool is returned. If the string does not exist, a reference to str is added to the intern pool, then that reference is returned. .... If you are trying to reduce the total amount of memory your application allocates, keep in mind that interning a string has two unwanted side effects. First, the memory allocated for interned String objects is not likely be released until the common language runtime (CLR) terminates.

那么,这是否意味着 CLR 为所有正在运行的 .net 应用程序保留了一个实习生池? 示例:如果一个程序 A 创建了一个字符串文字“Test”,如果另一个程序试图创建另一个字符串文字“Test”,那么使用的是同一个副本吗?同样的问题也适用于 JVM。

最佳答案

CLR 为每个实例保留一个实习生池。如果您进一步阅读 MSDN link :

If you are trying to reduce the total amount of memory your application allocates, keep in mind that interning a string has two unwanted side effects. First, the memory allocated for interned String objects is not likely be released until the common language runtime (CLR) terminates.

对于 Java,它也是根据您启动的 JVM。

但是根据this article :

This myth goes in the opposite direction of myth 2. Some people belive that internalized strings stay in the memory until the JVM ends. It may have been true a long time ago, but today the internalized strings are garbage collected if there are no more references to them. See below a slightly modified version of the program above. It clears the references to internalized strings from time to time. If you follow the program execution from jconsole, you will see that the PermGen space usage goes up and down, as the Garbage Collector reclaims the memory used by the unreferenced internalized strings.

这意味着在 Java 中,驻留字符串实际上可以被 GC 处理。

关于c# - CLR/JVM 是否为所有正在运行的 .net/java 应用程序保留一个实习生池?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6568905/

相关文章:

c# - 在 C# 中查询 dBase 文件

java - 是否可以使用椭圆形 AbstractAnnotationCheck 设置多条消息?

c# - 在 C# 中更改进程名称?

c# - WCF反序列化如何在不调用构造函数的情况下实例化对象?

c# - 使用 Excel 互操作将 VBA 代码添加到 excel 文件

c# - 如何声明一个可以被每个方法使用的变量? | C#

java - DocumentBuilder 解析在命中 '&' 时中断字符串

java - 使用 KeyStore.getEntry() 时出现 UnsupportedOperationException?

.net - 如何学习ILGenerator编程?

C# 需要将 sql 中的数据放入 DataGridView 并按行的日期排序