From 8daad6ddd4bf83e294080aece013bfc0ed034a3e Mon Sep 17 00:00:00 2001 From: Mark Hansen Date: Tue, 9 Jul 2024 16:53:20 -0700 Subject: [PATCH] Avoid iterator allocations in FieldSet.writeField This is a performance optimisation. PiperOrigin-RevId: 650799480 --- .../src/main/java/com/google/protobuf/FieldSet.java | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 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 1ecab66b7c..8e5ca7cc08 100644 --- a/java/core/src/main/java/com/google/protobuf/FieldSet.java +++ b/java/core/src/main/java/com/google/protobuf/FieldSet.java @@ -722,6 +722,8 @@ final class FieldSet> { } /** Write a single field. */ + // Avoid iterator allocation. + @SuppressWarnings({"ForeachList", "ForeachListWithUserVar"}) public static void writeField( final FieldDescriptorLite descriptor, final Object value, final CodedOutputStream output) throws IOException { @@ -729,6 +731,7 @@ final class FieldSet> { int number = descriptor.getNumber(); if (descriptor.isRepeated()) { final List valueList = (List) value; + int valueListSize = valueList.size(); if (descriptor.isPacked()) { if (valueList.isEmpty()) { // The tag should not be written for empty packed fields. @@ -737,16 +740,19 @@ final class FieldSet> { output.writeTag(number, WireFormat.WIRETYPE_LENGTH_DELIMITED); // Compute the total data size so the length can be written. int dataSize = 0; - for (final Object element : valueList) { + for (int i = 0; i < valueListSize; i++) { + Object element = valueList.get(i); dataSize += computeElementSizeNoTag(type, element); } output.writeUInt32NoTag(dataSize); // Write the data itself, without any tags. - for (final Object element : valueList) { + for (int i = 0; i < valueListSize; i++) { + Object element = valueList.get(i); writeElementNoTag(output, type, element); } } else { - for (final Object element : valueList) { + for (int i = 0; i < valueListSize; i++) { + Object element = valueList.get(i); writeElement(output, type, number, element); } }