Open In App

Compact Strings in Java 9 with Examples

Prerequisites: String

Compact String is one of the performance enhancements introduced in the JVM as part of JDK 9. Till JDK 8, whenever we create one String object then internally it is represented as char[], which consist the characters of the String object.



What is the need of Compact String?

String class internal implementation before Java 9:




import java.io.Serializable;
  
public final class String
    implements Serializable,
               Comparable<String>,
               CharSequence {
  
    // The value is used
    // for character storage.
    private final char value[];
}

Note: In the above program, we can see that before Java 9, Java represent String object as a char[] only. Suppose we create one String object and object contains the characters which can be represented using 1 byte. Instead of representing the object as byte[] it will create char[] only, which will consume more memory.



JDK developers analyzed that most of the strings can be represented only using Latin-1 characters set. A Latin-1 char can be stored in one byte, which is exactly half of the size of char. This will improve the performance of String.

String class internal implementation from Java 9




import java.io.Serializable;
  
public final class String
    implements Serializable,
               Comparable<String>,
               CharSequence {
  
    private final byte[] value;
  
    private final byte coder;
}

Note: Now the question is how will it distinguish between the LATIN-1 and UTF-16 representations? Java developers introduced one final byte variable coder that preserves the information about characters representation. The value of coder value can be:

static final byte LATIN1 = 0;
static final byte UTF16 = 1;

Thus, the new String implementation known as Compact String in Java 9 is better than String before Java 9 in terms of performance because Compact String uses approximately the half area as compared with String in the heap from JDK 9.

Let’s see the difference of the memory used by a String object before Java 9 and from Java 9:




// Program to illustrate the memory
// used by String before Java 9
  
public class Geeks {
    public static void main(String[] args)
    {
        String s
            = new String("Geeksforgeeks");
    }
}

Key points to note when we are running on Java 8 or earlier:




// Program to illustrate the memory
// used by String from Java 9
  
public class Geeks {
    public static void main(String[] args)
    {
  
        String s1 = new String("Geeksforgeeks");
        String s2 = new String("Geeksforgeeks€");
    }
}

Key points to note when we are running on Java 9:


Article Tags :