From 09648b86f9a1bc5d3912408feb30bf099e1599a4 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Wed, 1 Apr 2026 10:56:45 -1000 Subject: [PATCH] [api] Combine reserve_and_resize + resize in encode_to_buffer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit For non-first batch messages, fold the payload resize into the reserve_and_resize call. This eliminates a redundant size() read, a redundant capacity check, and an extra jump on the hot path. Saves 17 bytes in encode_to_buffer (130 → 113) and ~5 instructions on the second-message path. --- esphome/components/api/api_connection.cpp | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/esphome/components/api/api_connection.cpp b/esphome/components/api/api_connection.cpp index 79df85ada35..f12141e197a 100644 --- a/esphome/components/api/api_connection.cpp +++ b/esphome/components/api/api_connection.cpp @@ -2023,19 +2023,21 @@ uint16_t APIConnection::encode_to_buffer(uint32_t calculated_size, MessageEncode auto &shared_buf = conn->parent_->get_shared_buffer_ref(); + size_t write_start; if (conn->flags_.batch_first_message) { // First message - buffer already prepared by caller, just clear flag conn->flags_.batch_first_message = false; + write_start = shared_buf.size(); + shared_buf.resize(write_start + calculated_size); } else { // Batch message second or later - // Add padding for previous message footer + this message header + // Reserve for full message, resize to include footer gap + header padding + payload size_t current_size = shared_buf.size(); - shared_buf.reserve_and_resize(current_size + total_calculated_size, current_size + footer_size + header_padding); + shared_buf.reserve_and_resize(current_size + total_calculated_size, + current_size + footer_size + header_padding + calculated_size); + write_start = shared_buf.size() - calculated_size; } - // Pre-resize buffer to include payload, then encode through raw pointer - size_t write_start = shared_buf.size(); - shared_buf.resize(write_start + calculated_size); ProtoWriteBuffer buffer{&shared_buf, write_start}; encode_fn(msg, buffer);