diff --git a/esphome/components/api/api_connection.cpp b/esphome/components/api/api_connection.cpp index c882d48112..a6e4e8bf9c 100644 --- a/esphome/components/api/api_connection.cpp +++ b/esphome/components/api/api_connection.cpp @@ -2072,6 +2072,14 @@ void APIConnection::on_fatal_error() { this->flags_.remove = true; } +void APIConnection::DeferredBatch::add_item_front(EntityBase *entity, uint8_t message_type, uint8_t estimated_size) { + // Swap to front avoids expensive vector::insert which shifts all elements + this->items.push_back({entity, message_type, estimated_size, AUX_DATA_UNUSED}); + if (this->items.size() > 1) { + std::swap(this->items.front(), this->items.back()); + } +} + bool APIConnection::send_message_smart_(EntityBase *entity, uint8_t message_type, uint8_t estimated_size, uint8_t aux_data_index) { if (this->should_send_immediately_(message_type) && this->helper_->can_write_without_blocking()) { diff --git a/esphome/components/api/api_connection.h b/esphome/components/api/api_connection.h index 776b67738c..c39ae47bc9 100644 --- a/esphome/components/api/api_connection.h +++ b/esphome/components/api/api_connection.h @@ -659,13 +659,8 @@ class APIConnection final : public APIServerConnectionBase { this->items.push_back({entity, message_type, estimated_size, aux_data_index}); } // Add item to the front of the batch (for high priority messages like ping) - void add_item_front(EntityBase *entity, uint8_t message_type, uint8_t estimated_size) { - // Swap to front avoids expensive vector::insert which shifts all elements - this->items.push_back({entity, message_type, estimated_size, AUX_DATA_UNUSED}); - if (this->items.size() > 1) { - std::swap(this->items.front(), this->items.back()); - } - } + // Out-of-line: called from cold paths (on_shutdown, check_keepalive_) + void add_item_front(EntityBase *entity, uint8_t message_type, uint8_t estimated_size); // Clear all items void clear() {