From 45cf5ce12b9bc859f6792fc0dc072eb7bbd21e30 Mon Sep 17 00:00:00 2001 From: firewave Date: Thu, 1 Aug 2024 00:44:47 +0200 Subject: [PATCH] ProgramMemory: avoid unnecessary copy in `erase_if()` [skip ci] --- lib/programmemory.cpp | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/lib/programmemory.cpp b/lib/programmemory.cpp index af86ef98318..b2418cce868 100644 --- a/lib/programmemory.cpp +++ b/lib/programmemory.cpp @@ -173,10 +173,32 @@ void ProgramMemory::erase_if(const std::function& pred if (mValues->empty()) return; - // TODO: how to delay until we actuallly modify? - copyOnWrite(); + auto it = std::find_if(mValues->cbegin(), mValues->cend(), [&pred](const std::pair& entry) { + return pred(entry.first); + }); + if (it == mValues->cend()) + return; + + if (mValues.use_count() == 1) + { + it = mValues->erase(it); + } + else + { + const auto& exprIdTok = it->first; + + copyOnWrite(); + + it = mValues->cbegin(); + for (; it != mValues->cend(); ++it) { + if (it->first == exprIdTok) { + it = mValues->erase(it); + break; + } + } + } - for (auto it = mValues->begin(); it != mValues->end();) { + for (; it != mValues->cend();) { if (pred(it->first)) it = mValues->erase(it); else