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?
char is a primitive data type whereas String is a class in java. char represents a single character whereas String can have zero or more characters. So String is an array of chars. We define char in java program using single quote (') whereas we can define String in Java using double quotes (").
We can use profilers for this. A Java Profiler is a tool that monitors Java bytecode constructs and operations at the JVM level. These code constructs and operations include object creation, iterative executions (including recursive calls), method executions, thread executions, and garbage collections.
Memory profiling enables you to understand the memory allocation and garbage collection behavior of your applications over time. It helps you identify method calls in the context within which most memory was allocated and combine this information with the number of allocated objects.
Does String s = "some text" create a char[]?
This doesn't create any objects.
I've noticed there's hundreds of String s = new String("some text") with no apparent reason. Is this the culprit?
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 use byte[]
instead of char[]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With