Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8369564

Provide a MemorySegment API to read and write strings with known lengths

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Unresolved
    • Icon: P4 P4
    • None
    • None
    • core-libs

      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, after JDK-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.

            Unassigned Unassigned
            cushon Liam Miller-Cushon
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated: