gpt4 book ai didi

java - 相对于 JVM 的字符串池,在 Java 中创建一个字符串的时间成本是多少?

转载 作者:行者123 更新时间:2023-11-29 06:36:28 24 4
gpt4 key购买 nike

Java 有一个字符串池,因此在实际创建新字符串之前,我想有一个检查来查看相同的字符串是否已经存在,这个调用的成本是多少?

池是哈希结构还是树结构?

无论哪种情况,我想都归结为字符串哈希码的性能,因为搜索树使用哈希码作为键?

我猜它大约是 log n,其中 n 是当前堆上的字符串数。

最佳答案

来自 this unofficial blog

Java Virtual Machine maintains an internal list of references for interned Strings ( pool of unique Strings) to avoid duplicate String objects in heap memory. Whenever the JVM loads String literal from class file and executes, it checks whether that String exists in the internal list or not. If it already exists in the list, then it does not create a new String and it uses reference to the existing String Object.

JVM does this type of checking internally for String literal but not for String object which it creates through 'new' keyword. You can explicitly force JVM to do this type of checking for String objects which are created through 'new' keyword using String.intern() method. This forces JVM to check the internal list and use the existing String object if it is already present.

关于java - 相对于 JVM 的字符串池,在 Java 中创建一个字符串的时间成本是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19906786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com