我正在分析一个应用程序并注意到 52% (195MB) 的内存被 char[]
使用,20% 被 String
使用。这是一个有很多依赖项的大型项目,我刚刚看到它,所以我有几个相关的问题可以帮助我开始:
String s = "some text"
是否创建了一个 char[]?
我注意到有数百个 String s = new String("some text")
没有明显的原因。这是罪魁祸首吗?
最佳答案
Does String s = "some text" create a char[]?
这不会创建任何对象。
I've noticed there's hundreds of String s = new String("some text") with no apparent reason. Is this the culprit?
这会创建 String 的副本,可能还会创建 char[](两个对象)。仅当字符串表示另一个字符串的子字符串时才进行复制。
我会确保你有一个支持 -XX:+UseCompressedStrings
的 Java 版本 这在更高版本的 Java 中默认打开并允许 JVM 使用 byte[]
而不是 char[]
,它可以是大小的一半。
但是,如今 400 MB 并不算大,购买更多内存可能是最简单的解决方案。只需 120 美元即可获得 16 GB。
关于java - 剖析 Java char[] 和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7887464/