From 55a76fcbca6cac5b743a374fd64b74a0fdc8a82d Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Tue, 17 Mar 2026 01:58:10 -1000 Subject: [PATCH] Change cleanup_() to return bool instead of size_t cleanup_() was computing items_.size() on every call even on the fast path where nothing was removed. All callers only check if items remain (== 0), so return bool and use items_.empty() instead. --- esphome/core/scheduler.cpp | 10 +++++----- esphome/core/scheduler.h | 4 ++-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/esphome/core/scheduler.cpp b/esphome/core/scheduler.cpp index a3a767a17b..db40ede78c 100644 --- a/esphome/core/scheduler.cpp +++ b/esphome/core/scheduler.cpp @@ -396,7 +396,7 @@ optional HOT Scheduler::next_schedule_in(uint32_t now) { // safe when called from the main thread. Other threads must not call this method. // If no items, return empty optional - if (this->cleanup_() == 0) + if (!this->cleanup_()) return {}; SchedulerItem *item = this->items_[0]; @@ -633,12 +633,12 @@ void HOT Scheduler::process_to_add() { this->to_add_.clear(); this->to_add_count_clear_(); } -size_t HOT Scheduler::cleanup_() { - // Fast path: if nothing to remove, just return the current size. +bool HOT Scheduler::cleanup_() { + // Fast path: if nothing to remove, just check if items exist. // Uses atomic load on platforms with atomics, falls back to always taking the lock otherwise. // Worst case is a one-loop-iteration delay in cleanup. if (this->to_remove_empty_()) - return this->items_.size(); + return !this->items_.empty(); // We must hold the lock for the entire cleanup operation because: // 1. We're modifying items_ (via pop_raw_locked_) which requires exclusive access @@ -656,7 +656,7 @@ size_t HOT Scheduler::cleanup_() { this->to_remove_decrement_(); this->recycle_item_main_loop_(this->pop_raw_locked_()); } - return this->items_.size(); + return !this->items_.empty(); } Scheduler::SchedulerItem *HOT Scheduler::pop_raw_locked_() { std::pop_heap(this->items_.begin(), this->items_.end(), SchedulerItem::cmp); diff --git a/esphome/core/scheduler.h b/esphome/core/scheduler.h index d00673f403..32fa807473 100644 --- a/esphome/core/scheduler.h +++ b/esphome/core/scheduler.h @@ -284,9 +284,9 @@ class Scheduler { #endif } // Cleanup logically deleted items from the scheduler - // Returns the number of items remaining after cleanup + // Returns true if items remain after cleanup // IMPORTANT: This method should only be called from the main thread (loop task). - size_t cleanup_(); + bool cleanup_(); // Remove and return the front item from the heap as a raw pointer. // Caller takes ownership and must either recycle or delete the item. // IMPORTANT: Caller must hold the scheduler lock before calling this function.