Difference between compact strings and compressed strings in Java 9

Viewed 7936

What are the advantages of compact strings over compressed strings in JDK9?

4 Answers

Compressed Strings (-XX:+UseCompressedStrings)

This was a optional feature introduced in Java 6 Update 21 to improve SPECjbb performance by encoding only US-ASCII String on a byte per character.

This feature can be enabled by an -XX flag (-XX:+UseCompressedStrings). When it is enabled, String.value was changed to an Object reference and would point either to a byte[], for strings containing only 7-bit US-ASCII characters, or else a char[].

Later it was removed in Java 7 because of high maintenance and hard to test.

Compact String

This is a new feature introduced in Java 9 to build a memory efficient String.

Before Java 9, the String class stored characters in a char array, using two bytes for each character but from Java 9 the new String class will store characters in byte[](one byte per character) or char[](two bytes per character), based upon the contents of the string, plus an encoding-flag field. If String characters are of type Latin-1 then byte[] will be used else if characters are of type UTF-16 then char[] will be used. The encoding flag will indicate which encoding is used.

Related