分析 Java char[] 和字符串
我正在分析一个应用程序,发现 52% (195MB) 的内存被 char[]
使用,20% 被 String
使用。这是一个具有很多依赖项的大型项目,我刚刚看到它,所以我有几个相关的问题可以帮助我开始:
String s = "some text"
创建一个 char[ ]?
我注意到有数百个 String s = new String("some text")
没有明显的原因。这就是罪魁祸首吗?
I am profiling an application and noticed that 52% (195MB) of the memory is being used by char[]
and 20% by String
. This is a large project with a lot of dependencies and I've just seen it so I have a couple of related questions to help me get started:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不会创建任何对象。
这将创建 String 的副本以及可能的 char[] (两个对象)。仅当该字符串表示另一个字符串的子字符串时才会获取副本。
我会确保你有一个支持
-XX:+UsecompressedStrings
的 Java 版本,在更高版本的 Java 中默认启用此功能,并允许 JVM 使用byte[]
代替char[]
的大小可以是一半。然而,如今 400 MB 已经不算大了,购买更多内存可能是最简单的解决方案。您只需 120 美元即可获得 16 GB 存储空间。
This doesn't create any objects.
This creates a copy of the String and possibly the char[] (two objects). A copy is only taken if the String represents the substring of another string.
I would ensure you have a version of Java which supports
-XX:+UseCompressedStrings
This is on by default in later versions of Java and allows the JVM to usebyte[]
instead ofchar[]
which can be half the size.However, 400 MB isn't that big these days and buy more memory may be the simplest solution. You can get 16 GB for as little as $120.