From f9ecda5f3cab9705f5bf1aa810c76183cf8b8db3 Mon Sep 17 00:00:00 2001 From: Mark Hansen Date: Wed, 31 Jul 2024 14:12:47 -0700 Subject: [PATCH] Reuse empty int[0] in MessageSchema.intValue to save allocations This should save a little memory. We've observed hundreds of such empty arrays in some applications. This affects non-empty messages with none of: - repeated fields - map fields - fields to check if they're initialized PiperOrigin-RevId: 658137927 --- .../com/google/protobuf/MessageSchema.java | 28 +++++++++++-------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/java/core/src/main/java/com/google/protobuf/MessageSchema.java b/java/core/src/main/java/com/google/protobuf/MessageSchema.java index f8f79fcdf8..b6ccc8329b 100644 --- a/java/core/src/main/java/com/google/protobuf/MessageSchema.java +++ b/java/core/src/main/java/com/google/protobuf/MessageSchema.java @@ -700,17 +700,23 @@ final class MessageSchema implements Schema { if (repeatedFieldOffsets == null) { repeatedFieldOffsets = EMPTY_INT_ARRAY; } - int[] combined = - new int[checkInitialized.length + mapFieldPositions.length + repeatedFieldOffsets.length]; - System.arraycopy(checkInitialized, 0, combined, 0, checkInitialized.length); - System.arraycopy( - mapFieldPositions, 0, combined, checkInitialized.length, mapFieldPositions.length); - System.arraycopy( - repeatedFieldOffsets, - 0, - combined, - checkInitialized.length + mapFieldPositions.length, - repeatedFieldOffsets.length); + int combinedLength = + checkInitialized.length + mapFieldPositions.length + repeatedFieldOffsets.length; + int[] combined; + if (combinedLength > 0) { + combined = new int[combinedLength]; + System.arraycopy(checkInitialized, 0, combined, 0, checkInitialized.length); + System.arraycopy( + mapFieldPositions, 0, combined, checkInitialized.length, mapFieldPositions.length); + System.arraycopy( + repeatedFieldOffsets, + 0, + combined, + checkInitialized.length + mapFieldPositions.length, + repeatedFieldOffsets.length); + } else { + combined = EMPTY_INT_ARRAY; + } return new MessageSchema( buffer,