Lower overhead String encoding/decoding
richard.warburton at gmail.com
Mon Sep 22 11:25:53 UTC 2014
A long-standing issue with Strings in Java is the ease and performance of
creating a String from a ByteBuffer. People who are using nio to bring in
data off the network will be receiving that data in the form of bytebuffers
and converting it to some form of String. For example restful systems
receiving XML or Json messages.
The current workaround is to create a byte from the ByteBuffer - a
copying action for any direct bytebuffer - and then pass that to the
String. I'd like to propose that we add an additional constructor to the
String class that takes a ByteBuffer as an argument, and directly create
the char value inside the String from the ByteBuffer.
Similarly if you have a String that you want to encode onto the wire then
you need to call String.getBytes(), then write your byte into a
ByteBuffer or send it over the network. This ends up allocating a byte to
do the copy and also trimming the byte back down again, usually
allocating another byte. To address this problem I've added a couple of
getBytes() overloads that take byte and ByteBuffer arguments and write
directly to those buffers.
I've put together a patch that implements this to demonstrate the overall
I'm happy to take any feedback on direction or the patch itself or the
overall idea/approach. I think there are a number of similar API situations
in other places as well, for example StringBuffer/StringBuilder instances
which could have similar appends directly from ByteBuffer instances instead
of byte instances.
I'll also be at Javaone next week, so if you want to talk about this, just
let me know.
PS: I appreciate that since I'm adding a method to the public API which
consequently requires standardisation but I think that this could get
incorporated into the Java 9 umbrella JSR.
More information about the core-libs-dev