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 f536be2640..9ddf548865 100644 --- a/java/core/src/main/java/com/google/protobuf/FieldSet.java +++ b/java/core/src/main/java/com/google/protobuf/FieldSet.java @@ -264,7 +264,8 @@ final class FieldSet> { /** * Useful for implementing {@link Message.Builder#setField(Descriptors.FieldDescriptor,Object)}. */ - @SuppressWarnings({"unchecked", "rawtypes"}) + // Avoid iterator allocation. + @SuppressWarnings({"ForeachList", "ForeachListWithUserVar"}) public void setField(final T descriptor, Object value) { if (descriptor.isRepeated()) { if (!(value instanceof List)) { @@ -274,10 +275,14 @@ final class FieldSet> { // Wrap the contents in a new list so that the caller cannot change // the list's contents after setting it. - final List newList = new ArrayList<>(); - newList.addAll((List) value); - for (final Object element : newList) { + List list = (List) value; + int listSize = list.size(); + // Avoid extra allocations: no iterator, no intermediate array copy. + final List newList = new ArrayList<>(listSize); + for (int i = 0; i < listSize; i++) { + Object element = list.get(i); verifyType(descriptor, element); + newList.add(element); } value = newList; } else {