java – 什么是String interning?

什么是String在Java中的实现,当我应该使用它,为什么?
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#intern()

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

这可以有助于减少程序的内存需求。但是请注意,缓存由永久内存池中的JVM维护,通常与堆相比大小有限,因此如果没有太多重复值,则不应使用intern。

更多关于使用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

更新:内部字符串存储在Java 7以后的主堆中。 http://www.oracle.com/technetwork/java/javase/jdk7-relnotes-418459.html#jdk7changes

http://stackoverflow.com/questions/10578984/what-is-string-interning

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:java – 什么是String interning?