How to avoid a copy of array when parsing a ByteString with ScalaPB

138 Views Asked by At

Given bs, an instance of com.google.protobuf.ByteString.

What is the best way to parse from it

I have tried

  1. Foo.parseFrom(bs.toByteArray)
  2. Foo.parseFrom(bs.newInput)

Surprisingly, a JMH benchmark shows that 1. is faster (I would have expected to avoid instantiating a new array with 2.).

Is there a better way ?

1

There are 1 best solutions below

0
Yann Moisan On

The fastest way it to use newCodedInput.

In my test, the concrete implementation of ByteString is com.google.protobuf.ByteString$LiteralByteString

Looking at the code, we can see that the copy is avoided

@Override
public final CodedInputStream newCodedInput() {
  // We trust CodedInputStream not to modify the bytes, or to give anyone
  // else access to them.
  return CodedInputStream.newInstance(
      bytes, getOffsetIntoBytes(), size(), /* bufferIsImmutable= */ true);
}