diff --git a/esphome/components/api/__init__.py b/esphome/components/api/__init__.py index e91e922204..cf95da1bf0 100644 --- a/esphome/components/api/__init__.py +++ b/esphome/components/api/__init__.py @@ -265,6 +265,8 @@ async def to_code(config): cg.add_define("USE_API_HOMEASSISTANT_STATES") if actions := config.get(CONF_ACTIONS, []): + # Collect all triggers first, then register all at once with initializer_list + triggers: list[cg.Pvariable] = [] for conf in actions: template_args = [] func_args = [] @@ -278,8 +280,10 @@ async def to_code(config): trigger = cg.new_Pvariable( conf[CONF_TRIGGER_ID], templ, conf[CONF_ACTION], service_arg_names ) - cg.add(var.register_user_service(trigger)) + triggers.append(trigger) await automation.build_automation(trigger, func_args, conf) + # Register all services at once - single allocation, no reallocations + cg.add(var.initialize_user_services(triggers)) if CONF_ON_CLIENT_CONNECTED in config: cg.add_define("USE_API_CLIENT_CONNECTED_TRIGGER") diff --git a/esphome/components/api/api_server.h b/esphome/components/api/api_server.h index e0e23301d0..523a77262d 100644 --- a/esphome/components/api/api_server.h +++ b/esphome/components/api/api_server.h @@ -125,6 +125,9 @@ class APIServer : public Component, public Controller { #endif // USE_API_HOMEASSISTANT_ACTION_RESPONSES #endif // USE_API_HOMEASSISTANT_SERVICES #ifdef USE_API_SERVICES + void initialize_user_services(std::initializer_list services) { + this->user_services_.assign(services); + } void register_user_service(UserServiceDescriptor *descriptor) { this->user_services_.push_back(descriptor); } #endif #ifdef USE_HOMEASSISTANT_TIME