From caf9cbcd6356ddb993fdbab62106985426f7c179 Mon Sep 17 00:00:00 2001 From: Gregory Moskaliuk Date: Wed, 28 Oct 2026 10:42:57 +0100 Subject: [PATCH] Find a LongLivedObject in its collection without walking it (#59403) * Find a LongLivedObject in its collection without walking it LongLivedObjectCollection::remove walked the whole set to find the object, so releasing N pending callbacks or promises cost O(N^2). Look it up with a non-owning shared_ptr instead, which hashes and compares by the same pointer. Co-Authored-By: Claude Opus 5.5 * Name the lookup key in LongLivedObjectCollection::remove Address review: make it explicit that the key is a non-owning alias. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../ReactCommon/react/bridging/LongLivedObject.cpp | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/packages/react-native/ReactCommon/react/bridging/LongLivedObject.cpp b/packages/react-native/ReactCommon/react/bridging/LongLivedObject.cpp index 9c6d7c38d86..aa4b1fcdb58 100644 --- a/packages/react-native/ReactCommon/react/bridging/LongLivedObject.cpp +++ b/packages/react-native/ReactCommon/react/bridging/LongLivedObject.cpp @@ -36,11 +36,15 @@ void LongLivedObjectCollection::add(std::shared_ptr so) { void LongLivedObjectCollection::remove(const LongLivedObject* o) { std::scoped_lock lock(collectionMutex_); - for (auto p = collection_.begin(); p != collection_.end(); p++) { - if (p->get() == o) { - collection_.erase(p); - break; - } + // Empty owner: lookup-only alias, with no ownership or control block. + const std::shared_ptr lookupKey{ + std::shared_ptr{}, const_cast(o)}; + + // A shared_ptr hashes and compares by the pointer it stores, so a + // non-owning shared_ptr to `o` finds its entry without walking the set. + auto entry = collection_.find(lookupKey); + if (entry != collection_.end()) { + collection_.erase(entry); } }