Compact Strings in Java 9: How They Save Memory and Boost Performance
Starting with Java 9, the JVM quietly adopted a new internal representation for the java.lang.String class. The feature is called Compact Strings and, unless you went looking, you probably never noticed the change—yet it can shrink your application’s heap by 10-30% and speed up operations on text-heavy workloads. This post explains what compact strings are, how this subtle change delivers massive performance wins, and how you can measure the benefit on your own code. Get ready to reclaim your RAM! The Memory Drain Java 9 Tried to Solve Prior to JDK 9, every character inside a String was stored as a 16-bit char, using the UTF-16 encoding. The problem? For common languages like English, or text data formats like XML, JSON, log messages, and HTTP headers, most characters fall within the Latin-1 (ISO-8859-1) set, which perfectly fits into a single 8-bit byte. This meant that for a vast majority of applications, half of every character array was filled with redundant zeroes. That silent waste translated directly to: Larger Heap Footprint: Your application demands more RAM. More GC Pressure: The Garbage Collector has to work harder and longer. Lower CPU-Cache Locality: Data is scattered, slowing down processing. While developers could manually pack bytes, it came at the cost of code clarity and API compatibility. Clearly, a JVM-level fix was needed to make string handling efficient by default.