Why does the profiler show a large number of instances of char [] when I do not create them?

I am running a NetBeans profile of a recursive operation that involves creating a class with the java.lang.String field. In the class list, in the dump of the profile heap, the number of String fields corresponds to the number of classes created as expected, but there are also the number of char[] instances. Char arrays make up almost 70% of memory usage (!), While a String field is about 7%.

What's going on here? And how to reduce the number of instances of char[] ?

thanks

+6
java profiling
source share
4 answers

See Source Code String . The String object itself contains a cache hash code, the number of characters (again for optimization purposes), the offset (since a String.substr() indicates the original string data), and an array of characters that contains the actual string data. Therefore, your indicators showing that String consumes relatively little, but most of the memory is taken from the base character arrays.

+13
source share

Char arrays make up almost 70% of memory usage (!), While a string field is about 7%

This is the subtlety of memory profiling, known as "saved size" and "small size":

  • Shallow size refers to how much memory an object occupies, not including any child objects that it contains. This basically means primitive fields.
  • The saved size is the small size plus the size of other objects referenced by the object, but only those other objects that relate only to this object (it is difficult to explain, a simple concept).

A string is a great example. It contains several primitive fields, plus char[] . char[] takes into account the vast majority of memory usage. The shallow size of the String is very small, but it has kept the size much larger since this includes char[] .

The NetBeans profiler probably gives you a small size, which is not very useful, but easy to calculate. The saved size will include the use of char[] memory in the use of String memory, but calculating the stored size is expensive computational, and therefore profilers will not work until explicitly specified.

+3
source share

The String class in the Sun Java implementation uses char[] to store character data.

I believe this can be verified without looking at the source code, using a debugger to look at the contents of a String , or using reflection to look at the insides of a String object.

Therefore, it would be difficult to reduce the number of char[] being created if the number of String instances being created was not reduced.

+2
source share

Strings are supported by char arrays, so I don't think you can reduce the number of instances of char [] without decreasing your strings.

Have you tried to delete some lines to see if char [] s also goes?

+1
source share

All Articles