From 0bc18a82814ea7cfec35facd143e1316fd6414a1 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sat, 5 Jul 2025 23:34:55 -0500 Subject: [PATCH] Eliminate API component guard variable to save 8 bytes RAM (#9341) --- esphome/components/api/api_server.cpp | 8 ++++++++ esphome/components/api/api_server.h | 12 ++++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/esphome/components/api/api_server.cpp b/esphome/components/api/api_server.cpp index 0fd9c1a228..4dc6fe2390 100644 --- a/esphome/components/api/api_server.cpp +++ b/esphome/components/api/api_server.cpp @@ -24,6 +24,14 @@ static const char *const TAG = "api"; // APIServer APIServer *global_api_server = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) +#ifndef USE_API_YAML_SERVICES +// Global empty vector to avoid guard variables (saves 8 bytes) +// This is initialized at program startup before any threads +static const std::vector empty_user_services{}; + +const std::vector &get_empty_user_services_instance() { return empty_user_services; } +#endif + APIServer::APIServer() { global_api_server = this; // Pre-allocate shared write buffer diff --git a/esphome/components/api/api_server.h b/esphome/components/api/api_server.h index 9dc2b4b7d6..f34fd55974 100644 --- a/esphome/components/api/api_server.h +++ b/esphome/components/api/api_server.h @@ -25,6 +25,11 @@ struct SavedNoisePsk { } PACKED; // NOLINT #endif +#ifndef USE_API_YAML_SERVICES +// Forward declaration of helper function +const std::vector &get_empty_user_services_instance(); +#endif + class APIServer : public Component, public Controller { public: APIServer(); @@ -151,8 +156,11 @@ class APIServer : public Component, public Controller { #ifdef USE_API_YAML_SERVICES return this->user_services_; #else - static const std::vector EMPTY; - return this->user_services_ ? *this->user_services_ : EMPTY; + if (this->user_services_) { + return *this->user_services_; + } + // Return reference to global empty instance (no guard needed) + return get_empty_user_services_instance(); #endif }