From ce4d422da8341851a331633705911e78d71f2003 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Tue, 2 Sep 2025 10:06:51 -0500 Subject: [PATCH] comments --- esphome/core/scheduler.cpp | 5 +++++ esphome/core/scheduler.h | 9 ++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/esphome/core/scheduler.cpp b/esphome/core/scheduler.cpp index 3616bbc70a..7e2a805793 100644 --- a/esphome/core/scheduler.cpp +++ b/esphome/core/scheduler.cpp @@ -759,6 +759,11 @@ void Scheduler::recycle_item_(std::unique_ptr item) { if (!item) return; + // Pool size of 8 is a balance between memory usage and performance: + // - Small enough to not waste memory on simple configs (1-2 timers) + // - Large enough to handle complex setups with multiple sensors/components + // - Prevents system-wide stalls from heap allocation/deallocation that can + // disrupt task synchronization and cause dropped events static constexpr size_t MAX_POOL_SIZE = 8; if (this->scheduler_item_pool_.size() < MAX_POOL_SIZE) { // Clear callback to release captured resources diff --git a/esphome/core/scheduler.h b/esphome/core/scheduler.h index 70d114c488..50cc8da366 100644 --- a/esphome/core/scheduler.h +++ b/esphome/core/scheduler.h @@ -322,7 +322,14 @@ class Scheduler { #endif /* ESPHOME_THREAD_SINGLE */ uint32_t to_remove_{0}; - // Memory pool for recycling SchedulerItem objects + // Memory pool for recycling SchedulerItem objects to reduce heap churn. + // Design decisions: + // - std::vector is used instead of a fixed array because many systems only need 1-2 scheduler items + // - The vector grows dynamically up to MAX_POOL_SIZE (8) only when needed, saving memory on simple setups + // - This approach balances memory efficiency for simple configs with performance for complex ones + // - The pool significantly reduces heap fragmentation which is critical because heap allocation/deallocation + // can stall the entire system, causing timing issues and dropped events for any components that need + // to synchronize between tasks (see https://github.com/esphome/backlog/issues/52) std::vector> scheduler_item_pool_; #ifdef ESPHOME_THREAD_MULTI_ATOMICS