From 33d4ac4064297d5ca8773dafddda20f65d42da6a Mon Sep 17 00:00:00 2001 From: Mark Hansen Date: Wed, 2 Oct 2024 20:55:43 -0700 Subject: [PATCH] Hoist AbstractBufferedEncoder.position to a field when reading/writing it repeatedly. This produces much better code for Android: https://godbolt.org/z/xE8T9xqrr Down from 196 bytes to 140 bytes. Bounds checks get combined together. This is a partial roll-forward of cl/673588324. PiperOrigin-RevId: 681703327 --- .../src/main/java/com/google/protobuf/CodedOutputStream.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java b/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java index 683f3106fc..d3e7cc051e 100644 --- a/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java +++ b/java/core/src/main/java/com/google/protobuf/CodedOutputStream.java @@ -2365,10 +2365,12 @@ public abstract class CodedOutputStream extends ByteOutput { * responsibility of the caller. */ final void bufferFixed32NoTag(int value) { + int position = this.position; // Perf: hoist field to register to avoid load/stores. buffer[position++] = (byte) (value & 0xFF); buffer[position++] = (byte) ((value >> 8) & 0xFF); buffer[position++] = (byte) ((value >> 16) & 0xFF); buffer[position++] = (byte) ((value >> 24) & 0xFF); + this.position = position; totalBytesWritten += FIXED32_SIZE; } @@ -2377,6 +2379,7 @@ public abstract class CodedOutputStream extends ByteOutput { * responsibility of the caller. */ final void bufferFixed64NoTag(long value) { + int position = this.position; // Perf: hoist field to register to avoid load/stores. buffer[position++] = (byte) (value & 0xFF); buffer[position++] = (byte) ((value >> 8) & 0xFF); buffer[position++] = (byte) ((value >> 16) & 0xFF); @@ -2385,6 +2388,7 @@ public abstract class CodedOutputStream extends ByteOutput { buffer[position++] = (byte) ((int) (value >> 40) & 0xFF); buffer[position++] = (byte) ((int) (value >> 48) & 0xFF); buffer[position++] = (byte) ((int) (value >> 56) & 0xFF); + this.position = position; totalBytesWritten += FIXED64_SIZE; } }