-
Enhancement
-
Resolution: Unresolved
-
P4
-
None
-
None
After JDK-8333843, the javadoc for MemorySegment#getString suggests the following pattern for reading strings of known length:
byte[] bytes = new byte[length];
MemorySegment.copy(segment, JAVA_BYTE, offset, bytes, 0, length);
return new String(bytes, charset);
However this is less efficient than what the implementation of getString does, afterJDK-8362893 it uses JavaLangAccess::uncheckedNewStringNoRepl to avoid the copy.
It is possible that in the future C2 will be able to optimize away the copy for the known length pattern (see JDK-8364418), but it can't do that for current JDK versions, and it sounds like there are some challenges to doing that optimization.
Given all that, I think it makes sense to reconsider the possibility of adding an overload of MemorySegment#getString to read strings with known lengths, which would offer the same performance as the null-terminated getString, and avoid the copy of the byte[].
Additionally, the setString implementation uses optimizations in StringSupport for the case where the underlying bytes are compatible, but only supports null-terminated strings. It would be nice to offer an overload of setString as well for strings of known length.
byte[] bytes = new byte[length];
MemorySegment.copy(segment, JAVA_BYTE, offset, bytes, 0, length);
return new String(bytes, charset);
However this is less efficient than what the implementation of getString does, after
It is possible that in the future C2 will be able to optimize away the copy for the known length pattern (see JDK-8364418), but it can't do that for current JDK versions, and it sounds like there are some challenges to doing that optimization.
Given all that, I think it makes sense to reconsider the possibility of adding an overload of MemorySegment#getString to read strings with known lengths, which would offer the same performance as the null-terminated getString, and avoid the copy of the byte[].
Additionally, the setString implementation uses optimizations in StringSupport for the case where the underlying bytes are compatible, but only supports null-terminated strings. It would be nice to offer an overload of setString as well for strings of known length.
- relates to
-
JDK-8364418 C2 fails to optimize away an array that does not escape
-
- Open
-
-
JDK-8362893 Improve performance for MemorySegment::getString
-
- Resolved
-
-
JDK-8333843 Provide guidelines on MemorySegment to read strings with known lengths
-
- Resolved
-