Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Profiling Java char[] and Strings

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?

like image 594
Michael Avatar asked Oct 25 '11 09:10

Michael


People also ask

What is a difference between string and char [] in Java?

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 (").

How do you code profiling in Java?

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.

What is memory profiling in Java?

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.


1 Answers

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.

like image 84
Peter Lawrey Avatar answered Sep 19 '22 00:09

Peter Lawrey