java - 当我们有字符串池时为什么要进行字符串重复数据删除

标签 java string garbage-collection g1gc

String De-duplication :

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 - 当我们有字符串池时为什么要进行字符串重复数据删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42911701/

相关文章:

c - 填空: Reverse the original string without asking other than what is given?

ios - 如何在 Swift 中的 UITextField 上应用手机号码模式

java - NamedNodeMap 的通用 foreach 迭代

java - 在javafx的场景构建器中调用带有参数的方法

php - 描述计算文本相似度的 PHP 算法的论文 "Oliver [1993]"是什么?

java - 可以在两次后续调用 Wea​​kReference.get() 之间对对象进行垃圾回收吗?

Python脚本在不同的行停止并且不抛出异常

.net - [垃圾收集] dotTrace Performance Profiler 是什么意思?

java - 什么是NullPointerException,我该如何解决?

java - Pydoop Java home not set 安装问题