-1

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 ?

Yann Moisan
  • 8,161
  • 8
  • 47
  • 91

1 Answers1

1

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);
}
Yann Moisan
  • 8,161
  • 8
  • 47
  • 91