编程语言
首页 > 编程语言> > 什么是Java String interning?

什么是Java String interning?

作者:互联网

什么是Java中的String Interning,何时应该使用它,为什么?

解决方法:

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#intern()

基本上对一系列字符串执行String.intern()将确保具有相同内容的所有字符串共享相同的内存.因此,如果您有’john’出现1000次的名称列表,通过实习确保只有一个’john’实际分配了内存.

这对减少程序的内存要求很有用.但请注意,缓存由JVM在永久内存池中维护,与堆相比,其大小通常有限,因此如果没有太多重复值,则不应使用实习.

更多关于使用intern()的内存限制

On one hand, it is true that you can remove String duplicates by
internalizing them. The problem is that the internalized strings go to
the Permanent Generation, which is an area of the JVM that is reserved
for non-user objects, like Classes, Methods and other internal JVM
objects. The size of this area is limited, and is usually much smaller
than the heap. Calling intern() on a String has the effect of moving
it out from the heap into the permanent generation, and you risk
running out of PermGen space.


来自:http://www.codeinstructions.com/2009/01/busting-javalangstringintern-myths.html

从JDK 7(我的意思是在HotSpot中),有些东西发生了变化.

In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application. This change will result in more data residing in the main Java heap, and less data in the permanent generation, and thus may require heap sizes to be adjusted. Most applications will see only relatively small differences in heap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern() method will see more significant differences.

– 从Java SE 7 Features and Enhancements

更新:Interned字符串从Java 7开始存储在主堆中. http://www.oracle.com/technetwork/java/javase/jdk7-relnotes-418459.html#jdk7changes

标签:string-interning,java,string
来源: https://codeday.me/bug/20190911/1803091.html