From 4b7c2d43818a71e0c6975fcf3a1f1e0f1533ce3c Mon Sep 17 00:00:00 2001 From: Mark Hansen Date: Fri, 10 May 2024 08:33:09 -0700 Subject: [PATCH] Avoid allocating TreeMap in UnknownFieldSet.Builder.asMap If UnknownFieldSet is empty PiperOrigin-RevId: 632504647 --- .../src/main/java/com/google/protobuf/UnknownFieldSet.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/java/core/src/main/java/com/google/protobuf/UnknownFieldSet.java b/java/core/src/main/java/com/google/protobuf/UnknownFieldSet.java index aa71004da75f..2c21c5479400 100644 --- a/java/core/src/main/java/com/google/protobuf/UnknownFieldSet.java +++ b/java/core/src/main/java/com/google/protobuf/UnknownFieldSet.java @@ -483,6 +483,11 @@ public Builder addField(int number, Field field) { * changes may or may not be reflected in this map. */ public Map asMap() { + // Avoid an allocation for the common case of an empty map. + if (fieldBuilders.isEmpty()) { + return Collections.emptyMap(); + } + TreeMap fields = new TreeMap<>(); for (Map.Entry entry : fieldBuilders.entrySet()) { fields.put(entry.getKey(), entry.getValue().build());