0

Is there an approach that avoids having to copy byte[] from ByteBuffer with the ByteBuffer.get() operation.

I was looking at this post Java: Converting String to and from ByteBuffer and associated problems

and that causes an intermediary CharBuffer which I don't want as well.

I would like it to go from ByteBuffer to String.

When I know I have a byte[] underlying, this is easy with the code like so

new String(data, offset, length, charSet);

I was hoping for something similar with ByteBuffer. I am beginning to think this may not be possible? I need to decode N bytes of my ByteBuffer really.

This may be a bit of premature optimization but I am really just curious and wanted to test out the performance and squeeze every little bit out. (personal project really).

thanks, Dean

Community
  • 1
  • 1
Dean Hiller
  • 19,235
  • 25
  • 129
  • 212
  • 2
    Do you mean [ByteBuffer.array()](https://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html#array%28%29) ? – user3159253 Apr 11 '16 at 13:50

1 Answers1

2

Not really for a direct ByteBuffer, no. You need to have intermediate something, because String doesn't take a ByteBuffer as a constructor argument, and you can't wrap one (or even a char[]). If the buffer is non-direct, you can use the array() method to get a reference to the backing array (which isn't an intermediate array) and create a String out of that.

On the plus side, there's probably a lot more performance sensitive places in your project.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • well, I am playing with an nio library and testing shows the byte copying to be expensive :( so I was hoping to prevent more large byte array copies and go direct. It really seems like they should have this feature...shucks. – Dean Hiller Apr 13 '16 at 13:35
  • but yes, in the context of a full application stack, it would be minimal – Dean Hiller Apr 13 '16 at 13:35
  • I can imagine there can be some issues trying to create a Java `String` from basically unmanaged (as far as Java is concerned) memory without having any copying of bytes between. – Kayaman Apr 14 '16 at 06:04