diff --git a/esphome/components/api/api_connection.cpp b/esphome/components/api/api_connection.cpp index 45a9c120ee..357b6e1a32 100644 --- a/esphome/components/api/api_connection.cpp +++ b/esphome/components/api/api_connection.cpp @@ -1079,9 +1079,12 @@ void APIConnection::on_get_time_response(const GetTimeResponse &value) { homeassistant::global_homeassistant_time->set_epoch_time(value.epoch_seconds); #ifdef USE_TIME_TIMEZONE if (value.timezone_len > 0) { - std::string timezone_str(reinterpret_cast(value.timezone), value.timezone_len); - if (timezone_str != homeassistant::global_homeassistant_time->get_timezone()) { - homeassistant::global_homeassistant_time->set_timezone(timezone_str); + const std::string ¤t_tz = homeassistant::global_homeassistant_time->get_timezone(); + // Compare without allocating a string + if (current_tz.length() != value.timezone_len || + memcmp(current_tz.c_str(), value.timezone, value.timezone_len) != 0) { + homeassistant::global_homeassistant_time->set_timezone( + std::string(reinterpret_cast(value.timezone), value.timezone_len)); } } #endif @@ -1377,7 +1380,7 @@ void APIConnection::complete_authentication_() { } bool APIConnection::send_hello_response(const HelloRequest &msg) { - this->client_info_.name = std::string(reinterpret_cast(msg.client_info), msg.client_info_len); + this->client_info_.name.assign(reinterpret_cast(msg.client_info), msg.client_info_len); this->client_info_.peername = this->helper_->getpeername(); this->client_api_version_major_ = msg.api_version_major; this->client_api_version_minor_ = msg.api_version_minor;