Skip to content

Commit

Permalink
Reuse empty int[0] in MessageSchema.intValue to save allocations
Browse files Browse the repository at this point in the history
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
  • Loading branch information
mhansen authored and copybara-github committed Jul 31, 2024
1 parent 6fdcc0b commit f9ecda5
Showing 1 changed file with 17 additions and 11 deletions.
28 changes: 17 additions & 11 deletions java/core/src/main/java/com/google/protobuf/MessageSchema.java
Original file line number Diff line number Diff line change
Expand Up @@ -700,17 +700,23 @@ static <T> MessageSchema<T> newSchemaForMessageInfo(
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<T>(
buffer,
Expand Down

0 comments on commit f9ecda5

Please sign in to comment.