From cc5eccfb2866f6bbcac047a107e75a5175bd1460 Mon Sep 17 00:00:00 2001 From: Mark Hansen Date: Tue, 9 Jul 2024 17:10:52 -0700 Subject: [PATCH] Avoid iterator allocations in FieldSet.computeFieldSize PiperOrigin-RevId: 650803788 --- .../core/src/main/java/com/google/protobuf/FieldSet.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/java/core/src/main/java/com/google/protobuf/FieldSet.java b/java/core/src/main/java/com/google/protobuf/FieldSet.java index 8e5ca7cc08..68b2cd119d 100644 --- a/java/core/src/main/java/com/google/protobuf/FieldSet.java +++ b/java/core/src/main/java/com/google/protobuf/FieldSet.java @@ -903,17 +903,21 @@ final class FieldSet> { } /** Compute the number of bytes needed to encode a particular field. */ + // Avoid iterator allocation. + @SuppressWarnings({"ForeachList", "ForeachListWithUserVar"}) public static int computeFieldSize(final FieldDescriptorLite descriptor, final Object value) { WireFormat.FieldType type = descriptor.getLiteType(); int number = descriptor.getNumber(); if (descriptor.isRepeated()) { List valueList = (List) value; + int valueListSize = valueList.size(); if (descriptor.isPacked()) { if (valueList.isEmpty()) { return 0; } int dataSize = 0; - for (final Object element : valueList) { + for (int i = 0; i < valueListSize; i++) { + Object element = valueList.get(i); dataSize += computeElementSizeNoTag(type, element); } return dataSize @@ -921,7 +925,8 @@ final class FieldSet> { + CodedOutputStream.computeUInt32SizeNoTag(dataSize); } else { int size = 0; - for (final Object element : valueList) { + for (int i = 0; i < valueListSize; i++) { + Object element = valueList.get(i); size += computeElementSize(type, number, element); } return size;