From 664baac09e97a9600554c0508eae020742f308d0 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Fri, 6 Feb 2026 20:32:04 +0100 Subject: [PATCH] [mqtt] Avoid heap allocation in on_log by using const char* publish overload The on_log callback was constructing a temporary MQTTMessage struct which copied the log_message_ topic string and created a new std::string from the message buffer on every log line. This is called frequently at runtime and contributes to heap fragmentation. Use the const char* publish overload directly to avoid both allocations. --- esphome/components/mqtt/mqtt_client.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/esphome/components/mqtt/mqtt_client.cpp b/esphome/components/mqtt/mqtt_client.cpp index d503461257..90b423c386 100644 --- a/esphome/components/mqtt/mqtt_client.cpp +++ b/esphome/components/mqtt/mqtt_client.cpp @@ -170,10 +170,8 @@ void MQTTClientComponent::send_device_info_() { void MQTTClientComponent::on_log(uint8_t level, const char *tag, const char *message, size_t message_len) { (void) tag; if (level <= this->log_level_ && this->is_connected()) { - this->publish({.topic = this->log_message_.topic, - .payload = std::string(message, message_len), - .qos = this->log_message_.qos, - .retain = this->log_message_.retain}); + this->publish(this->log_message_.topic.c_str(), message, message_len, this->log_message_.qos, + this->log_message_.retain); } } #endif