Avoid empty byte array allocations in Proto Lite toByteArray().

In AbstractMessageLite.toByteArray(), check if getSerializedSize() == 0 and return Internal.EMPTY_BYTE_ARRAY directly instead of allocating a new 0-byte array and CodedOutputStream wrappers.

PiperOrigin-RevId: 970010400
This commit is contained in:
Protobuf Team Bot 2026-08-24 12:32:35 -07:00 committed by Copybara-Service
parent 672eda6f1f
commit dee117a787

View file

@ -52,7 +52,11 @@ public abstract class AbstractMessageLite<
@Override
public byte[] toByteArray() {
try {
final byte[] result = new byte[getSerializedSize()];
final int size = getSerializedSize();
if (size == 0) {
return Internal.EMPTY_BYTE_ARRAY;
}
final byte[] result = new byte[size];
final CodedOutputStream output = CodedOutputStream.newInstance(result);
writeTo(output);
output.checkNoSpaceLeft();