Skip to content

Commit

Permalink
Avoid allocating FieldSet iterator if FieldSet is empty
Browse files Browse the repository at this point in the history
This saves some allocations during writing out messages with extensions declared in the common case of empty FieldSet.

PiperOrigin-RevId: 636031501
  • Loading branch information
mhansen authored and copybara-github committed May 22, 2024
1 parent 590e5aa commit 3ba7280
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions java/core/src/main/java/com/google/protobuf/FieldSet.java
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,10 @@ private static <T extends FieldDescriptorLite<T>> void cloneFieldEntry(
* library as it is not protected from mutation when fields is not immutable.
*/
public Iterator<Map.Entry<T, Object>> iterator() {
// Avoid allocation in the common case of empty FieldSet.
if (isEmpty()) {
return Collections.emptyIterator();
}
if (hasLazyField) {
return new LazyIterator<T>(fields.entrySet().iterator());
}
Expand All @@ -225,6 +229,10 @@ public Iterator<Map.Entry<T, Object>> iterator() {
* fields is not immutable.
*/
Iterator<Map.Entry<T, Object>> descendingIterator() {
// Avoid an allocation in the common case of empty FieldSet.
if (isEmpty()) {
return Collections.emptyIterator();
}
if (hasLazyField) {
return new LazyIterator<T>(fields.descendingEntrySet().iterator());
}
Expand Down

0 comments on commit 3ba7280

Please sign in to comment.