DEV Community

A N M Bazlur Rahman
A N M Bazlur Rahman

Posted on • Originally published at bazlur.com on

Reclaim 25% of Java Heap Memory and Lower Your Cloud Bills

You can save up to 25% of heap memory using latest java which means less cloud bills

Do you know that you can save up to 25% of your heap memory and your cloud bills without any effort?

Well, that’s true. Many exciting features have been added to the latest Java recently, and I’m going to cover one of them in this article, so please bear with me.

We all know, Strings are the most used object in any Java application. In fact, it takes up almost half of the heap size of a Java application. Did you know?

Before delving into this much further, let me answer your obvious question, which I know you’d ask: how are strings made of?

Well, Strings are nothing but an array of characters, well, at least it used to be. If you open the String class from JDK 8, you will be able to see it.

However, unlike C, an array of char is not a String in the Java programming language, and neither a String nor an array of char is terminated by ‘\u0000’ (the NUL character).

Nevertheless, a String object in Java is also immutable, which means the String content never changes, while an array of char has mutable elements.

Ref: https://docs.oracle.com/javase/specs/jls/se14/html/jls-10.html#jls-10.9

We will write about String immutability in another article. Rather get into the thing that I initially intended here.

In Java 8 and pre-Java 8, a char array is used in a String. A char takes 2 bytes of memory. That means, to store one character, you need 16 bits of memory. For example, if you write “Hello” you’d need an object of an array, and that would have 5 characters

The total size of a String = size of array object itself + size of 5 characters + array holds an integer for its length

= 8 bytes for array object header + 5 * 2bytes + 4 bytes

= 8 + 10 + 4

= 22 bytes

However, most western locals nowadays need only 8 bits byte array to encode them. That’s why Java 11 introduces the new compact strings that encode a string with an 8-bit byte array instead of a char array. Unless they explicitly need 16-bit characters. These strings are known as compact strings.

Hence, the size of an average string in java 11 is roughly half the size of the same thing in java 8.

On average, 50% of a typical Java heap may be consumed by string objects. This will vary from application to application, but on average, the heap requirement for such a program running with java 11 is only 75% of that same program running in java 8.

This is huge savings.

The -XX:+CompactStrings flag controls this feature

If you want to disable it, you can use this flag -XX:-CompactStrings.

That’s all for today.

Top comments (0)