> On Dec 24, 2021, at 2:46 PM, liangchenb...@gmail.com wrote: > >> Are you saying that new would always create a new object but the GC might >> merge multiple instances of String into a single instance? > > About jvm's string optimizations, jvm may make different string > objects with the same content share the backing array in order to > reduce allocation (like what the original poster alan wonders). This > optimization does not alter the identity of the relative string > objects and thus has zero effect on the user end.
For HotSpot this is enabled by -XX:+UseStringDeduplication. For more details see https://openjdk.java.net/jeps/192 Note that as of JDK 18 all of the HotSpot collectors support this, not just G1.