java – 为什么我们有字符串池时的字符串重复数据删除
作者:互联网
Strings consume a lot of memory in any application.Whenever the garbage collector visits String objects it takes note of the char arrays. It takes their hash value and stores it alongside with a weak reference to the array. As soon as it finds another String which has the same hash code it compares them char by char.If they match as well, one String will be modified and point to the char array of the second String. The first char array then is no longer referenced anymore and can be garbage collected.
字符串池:
All strings used by the java program are stored here. If two variables are initialized to the same string value. Two strings are not created in the memory, there will be only one copy stored in memory and both will point to the same memory location.
因此,java已经通过检查字符串池中是否存在字符串来解决不在堆中创建重复字符串的问题.那么字符串重复数据删除的目的是什么?
如果有如下代码
String myString_1 = new String("Hello World");
String myString_2 = new String("Hello World");
即使它们是相同的,也会在内存中创建两个字符串.除了这个字符串重复数据删除很有用之外,我想不出任何其他情况.显然我必须遗漏一些东西.我错过了什么?
提前致谢
解决方法:
字符串池仅适用于显式添加到其中的字符串,或者在应用程序中用作常量.它不适用于在应用程序生命周期内动态创建的字符串.但是,字符串重复数据删除适用于所有字符串.
标签:java,garbage-collection,string,g1gc 来源: https://codeday.me/bug/20190611/1217808.html