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 a8ba1bd4131a2..4c12486bd5531 100644 --- a/java/core/src/main/java/com/google/protobuf/FieldSet.java +++ b/java/core/src/main/java/com/google/protobuf/FieldSet.java @@ -213,6 +213,10 @@ private static > void cloneFieldEntry( * library as it is not protected from mutation when fields is not immutable. */ public Iterator> iterator() { + // Avoid allocation in the common case of empty FieldSet. + if (isEmpty()) { + return Collections.emptyIterator(); + } if (hasLazyField) { return new LazyIterator(fields.entrySet().iterator()); } @@ -225,6 +229,10 @@ public Iterator> iterator() { * fields is not immutable. */ Iterator> descendingIterator() { + // Avoid an allocation in the common case of empty FieldSet. + if (isEmpty()) { + return Collections.emptyIterator(); + } if (hasLazyField) { return new LazyIterator(fields.descendingEntrySet().iterator()); }