From 08a0994f4b11912f7dd81ad668a5649e83d9680e Mon Sep 17 00:00:00 2001 From: Mark Hansen Date: Tue, 9 Jul 2024 17:45:54 -0700 Subject: [PATCH] Avoid allocations in FieldSet.Builder.mergeFromField - Pre-size ArrayList - Avoid iterator allocation PiperOrigin-RevId: 650811055 --- .../src/main/java/com/google/protobuf/FieldSet.java | 10 +++++++--- 1 file changed, 7 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 ea59f8380b..0594cdb3b1 100644 --- a/java/core/src/main/java/com/google/protobuf/FieldSet.java +++ b/java/core/src/main/java/com/google/protobuf/FieldSet.java @@ -1319,7 +1319,8 @@ final class FieldSet> { } } - @SuppressWarnings("unchecked") + // Avoid iterator allocation. + @SuppressWarnings({"unchecked", "ForeachList", "ForeachListWithUserVar"}) private void mergeFromField(final Map.Entry entry) { final T descriptor = entry.getKey(); Object otherValue = entry.getValue(); @@ -1330,11 +1331,14 @@ final class FieldSet> { throw new IllegalStateException("Lazy fields can not be repeated"); } List value = (List) getFieldAllowBuilders(descriptor); + List otherList = (List) otherValue; + int otherListSize = otherList.size(); if (value == null) { - value = new ArrayList<>(); + value = new ArrayList<>(otherListSize); fields.put(descriptor, value); } - for (Object element : (List) otherValue) { + for (int i = 0; i < otherListSize; i++) { + Object element = otherList.get(i); value.add(FieldSet.cloneIfMutable(element)); } } else if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE) {