Skip to content

Commit 3ba7280

Browse files
mhansencopybara-github
authored andcommitted
Avoid allocating FieldSet iterator if FieldSet is empty
This saves some allocations during writing out messages with extensions declared in the common case of empty FieldSet. PiperOrigin-RevId: 636031501
1 parent 590e5aa commit 3ba7280

File tree

1 file changed

+8
-0
lines changed

1 file changed

+8
-0
lines changed

java/core/src/main/java/com/google/protobuf/FieldSet.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,10 @@ private static <T extends FieldDescriptorLite<T>> void cloneFieldEntry(
213213
* library as it is not protected from mutation when fields is not immutable.
214214
*/
215215
public Iterator<Map.Entry<T, Object>> iterator() {
216+
// Avoid allocation in the common case of empty FieldSet.
217+
if (isEmpty()) {
218+
return Collections.emptyIterator();
219+
}
216220
if (hasLazyField) {
217221
return new LazyIterator<T>(fields.entrySet().iterator());
218222
}
@@ -225,6 +229,10 @@ public Iterator<Map.Entry<T, Object>> iterator() {
225229
* fields is not immutable.
226230
*/
227231
Iterator<Map.Entry<T, Object>> descendingIterator() {
232+
// Avoid an allocation in the common case of empty FieldSet.
233+
if (isEmpty()) {
234+
return Collections.emptyIterator();
235+
}
228236
if (hasLazyField) {
229237
return new LazyIterator<T>(fields.descendingEntrySet().iterator());
230238
}

0 commit comments

Comments
 (0)