In JDK 25, we improved the performance of the class String in such a way that the String::hashCode function is mostly constant foldable. For example, if you use Strings as keys in a static unmodifiable Map, you will likely see significant performance improvements. Example Here is a relatively advanced example where we maintain an immutable Map of native calls, its keys are the name of the method call and the values are a MethodHandle that can be used to invoke the associated system call: // Set up an immutable Map of system calls static final Map<String, MethodHandle> SYSTEM_CALLS = Map.of( “malloc”, linker.downcallHandle(mallocSymbol,…), “free”, linker.downcallHandle(freeSymbol…), ...); … // Allocate a memory region of 16 bytes long address = SYSTEM_CALLS.get(“malloc”).invokeExact(16L); … // Free the memory region SYSTEM_CALLS.get(“free”).invokeExact(address); The method linker.downcallHandle(…) takes a symbol and additional parameters to bind a native call to a Java MethodHandle via the Foreign Function & Memory API introduced in JDK 22. This is a relatively slow process and involves spinning bytecode. However, once entered into the Map, the new performance improvements in the String class alone allow constant folding of both the key lookups and the values, thus improving performance by a factor of more than 8x: --- JDK 24 --- Benchmark Mode Cnt Score Error Units StringHashCodeStatic.nonZero avgt 15 4.632 ± 0.042 ns/op --- JDK 25 --- Benchmark Mode Cnt Score Error Units StringHashCodeStatic.nonZero avgt 15 0.571 ± 0.012 ns/op Note : the benchmarks above are not using a malloc() MethodHandle but an int identity function. After all, we are not testing the performance of malloc() but the actual String lookup and MethodHandle performance. This improvement will benefit any immutable Map<String, V> with Strings as keys and where values (of arbitrary type V) are looked up via constant Strings. How Does It Work? When a String is first created, its hashcode is unknown. On ...
First seen: 2025-05-02 19:42
Last seen: 2025-05-03 08:43