From 2137e4600acd1bcef97d715b99511b28e76cf102 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sat, 28 Mar 2026 17:37:45 -1000 Subject: [PATCH] [api] Hoist pos_ to local in encode_varint_raw_64 to avoid reload per byte MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use a __restrict__ local pointer for the varint write loop so the compiler can keep it in a register instead of reloading pos_ from memory on each iteration. Eliminates the store→load dependency chain that was causing 7 load/store pairs for a typical 48-bit BLE address varint. --- esphome/components/api/proto.h | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/esphome/components/api/proto.h b/esphome/components/api/proto.h index efec7af707..3989c7c424 100644 --- a/esphome/components/api/proto.h +++ b/esphome/components/api/proto.h @@ -224,13 +224,15 @@ class ProtoWriteBuffer { this->encode_varint_raw_slow_(value); } void encode_varint_raw_64(uint64_t value) { + // Use __restrict__ so the compiler knows pos doesn't alias this-> + // and can keep it in a register across the loop. + uint8_t *__restrict__ pos = this->pos_; while (value > 0x7F) { - this->debug_check_bounds_(1); - *this->pos_++ = static_cast(value | 0x80); + *pos++ = static_cast(value | 0x80); value >>= 7; } - this->debug_check_bounds_(1); - *this->pos_++ = static_cast(value); + *pos++ = static_cast(value); + this->pos_ = pos; } /** * Encode a field key (tag/wire type combination).