From 2f470ce5f2ef553ff748e2c7b124dedbd67d3b20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rub=C3=A9n=20Norte?= Date: Thu, 26 Nov 2026 06:24:52 -0800 Subject: [PATCH] Index MutationObserver child matching for wide lists (#60269) Summary: Pull Request resolved: https://github.com/react/react-native/pull/60269 ## Context When observed child vectors differ, MutationObserver searches the complete opposite list for every old and new child. After the shared-vector fast path, this remains quadratic work for appends, reorders and changes to one descendant of a wide observed node. ## Changes - Index new child families when both lists contain at least 16 children, reducing matching to expected linear time with temporary storage proportional to the new list. Keep the original linear searches for smaller lists. - Preserve the first matching new revision for each family, old-child traversal/removal order, new-child addition order, descendant-before-parent records and per-observer deduplication. Matches are not consumed, so repeated-family membership semantics remain unchanged. - Extend the existing public-API regression suite with mixed reorder/descendant/addition/removal cases at widths 15, 16 and 32, using Fantom's default development mode. ## Benchmark results Optimized native/JS code and Hermes bytecode, with MutationObserver enabled. These comparative measurements were collected at the preceding stable snapshot with the same observer implementations and benchmark fixtures: milliseconds of end-to-end update CPU time, aggregated as the median of three process runs' p50 values. Setup, reset renders, assertions and cleanup are outside the measured interval; reconciliation, observation, layout/mount work, record conversion and callback delivery are included. The parent already includes the shared-vector fast path. Reductions below compare indexed matching with that parent. | Workload | Children | Observers | Baseline (ms) | Parent: fast path (ms) | With indexed matching (ms) | Observed reduction vs. parent | | --- | ---: | ---: | ---: | ---: | ---: | ---: | | Append one child | 1,024 | 1 | 6.322 | 7.829 | 4.850 | 38.0% | | Add a grandchild in the last retained child | 1,024 | 1 | 6.271 | 6.623 | 4.883 | 26.3% | | Reverse retained children | 1,024 | 1 | 8.716 | 9.674 | 8.032 | 17.0% | | Replace all children | 1,024 | 1 | 30.210 | 32.900 | 29.119 | 11.5% | Relative to baseline, the complete stack reduced observed append latency by 23.3% and descendant-update latency by 22.1% at width 1,024. Property-only gains belong to the preceding fast path, not this index. All 47 scenarios passed in each of three timing runs per variant. Each scenario used at least 100 measured iterations, at least 250 ms measured execution, and 10 warmup iterations. These are synthetic measurements from one Linux worker, not isolated observer timings or device/app latency guarantees. Individual runs and unobserved controls varied; percentages are observed ratios of aggregate medians, not causal estimates or guaranteed speedups. The unobserved width-1,024 append control measured 4.094 / 4.431 / 3.990 ms across baseline / fast-path / indexed phases; the descendant control measured 3.908 / 4.268 / 4.056 ms. Controls are not perfectly stable, so the raw percentages should not be interpreted as isolated native speedups. The 16-child cutoff remains conservative rather than tuned. Changelog: [General][Changed] - Reduce `MutationObserver` child matching overhead for wide observed lists Reviewed By: javache Differential Revision: D134242657 --- .../observers/mutation/MutationObserver.cpp | 39 +++++++- .../__tests__/MutationObserver-itest.js | 99 +++++++++++++++++++ 2 files changed, 133 insertions(+), 5 deletions(-) diff --git a/packages/react-native/ReactCommon/react/renderer/observers/mutation/MutationObserver.cpp b/packages/react-native/ReactCommon/react/renderer/observers/mutation/MutationObserver.cpp index 2bc1036375d1..f850b14885ef 100644 --- a/packages/react-native/ReactCommon/react/renderer/observers/mutation/MutationObserver.cpp +++ b/packages/react-native/ReactCommon/react/renderer/observers/mutation/MutationObserver.cpp @@ -8,6 +8,7 @@ #include "MutationObserver.h" #include #include +#include namespace facebook::react { @@ -150,12 +151,38 @@ void MutationObserver::recordMutationsInSubtrees( return; } + struct ChildMatch { + size_t index; + bool seenInOld{false}; + }; + const bool useIndex = oldChildren.size() >= 16 && newChildren.size() >= 16; + std::unordered_map newChildMatches; + if (useIndex) { + newChildMatches.reserve(newChildren.size()); + for (size_t i = 0; i < newChildren.size(); ++i) { + newChildMatches.try_emplace( + &newChildren[i]->getFamily(), ChildMatch{.index = i}); + } + } + + const auto findNewChild = [&](const ShadowNode& oldChild) { + if (!useIndex) { + return findNodeOfSameFamily(newChildren, oldChild); + } + const auto it = newChildMatches.find(&oldChild.getFamily()); + if (it == newChildMatches.end()) { + return std::shared_ptr{}; + } + it->second.seenInOld = true; + return newChildren[it->second.index]; + }; + std::vector> addedNodes; std::vector> removedNodes; // Check for removed nodes (and equal nodes for further inspection) - for (auto& oldChild : oldChildren) { - auto newChild = findNodeOfSameFamily(newChildren, *oldChild); + for (const auto& oldChild : oldChildren) { + const auto newChild = findNewChild(*oldChild); if (!newChild) { removedNodes.push_back(oldChild); } else if (observeSubtree) { @@ -171,9 +198,11 @@ void MutationObserver::recordMutationsInSubtrees( } // Check for added nodes - for (auto& newChild : newChildren) { - auto oldChild = findNodeOfSameFamily(oldChildren, *newChild); - if (!oldChild) { + for (const auto& newChild : newChildren) { + const bool isAdded = useIndex + ? !newChildMatches.at(&newChild->getFamily()).seenInOld + : !findNodeOfSameFamily(oldChildren, *newChild); + if (isAdded) { addedNodes.push_back(newChild); } } diff --git a/packages/react-native/src/private/webapis/mutationobserver/__tests__/MutationObserver-itest.js b/packages/react-native/src/private/webapis/mutationobserver/__tests__/MutationObserver-itest.js index 4d07791caf25..28b5262ff299 100644 --- a/packages/react-native/src/private/webapis/mutationobserver/__tests__/MutationObserver-itest.js +++ b/packages/react-native/src/private/webapis/mutationobserver/__tests__/MutationObserver-itest.js @@ -406,6 +406,105 @@ describe('MutationObserver', () => { expect([...secondRecords[0].removedNodes]).toEqual([node111]); }); + for (const width of [15, 16, 32]) { + it(`should preserve record order when ${width} children are reordered and mutated`, () => { + const root = Fantom.createRoot(); + const parentRef = createRef(); + const firstChangedIndex = 4; + const secondChangedIndex = 8; + const childRefs = Array.from({length: width}, () => + createRef(), + ); + const firstDescendantRef = createRef(); + const secondDescendantRef = createRef(); + const firstAddedRef = createRef(); + const secondAddedRef = createRef(); + + Fantom.runTask(() => { + root.render( + + {childRefs.map((ref, i) => ( + + ))} + , + ); + }); + + const parent = nullthrows(parentRef.current); + const originalChildren = childRefs.map(ref => nullthrows(ref.current)); + let deepRecords: ReadonlyArray = []; + let shallowRecords: ReadonlyArray = []; + const deepObserver = new MutationObserver(records => { + deepRecords = records; + }); + const shallowObserver = new MutationObserver(records => { + shallowRecords = records; + }); + deepObserver.observe(parent, {childList: true, subtree: true}); + deepObserver.observe(originalChildren[firstChangedIndex], { + childList: true, + }); + shallowObserver.observe(parent, {childList: true}); + + Fantom.runTask(() => { + const updatedChildren = childRefs + .slice(2) + .map((ref, offset) => { + const i = offset + 2; + return ( + + {i === firstChangedIndex ? ( + + ) : null} + {i === secondChangedIndex ? ( + + ) : null} + + ); + }) + .reverse(); + root.render( + + {[ + , + ...updatedChildren, + , + ]} + , + ); + }); + + const nodes: ReadonlyArray = [ + parent, + ...originalChildren, + nullthrows(firstDescendantRef.current), + nullthrows(secondDescendantRef.current), + nullthrows(firstAddedRef.current), + nullthrows(secondAddedRef.current), + ]; + const summarizeRecord = (record: MutationRecordType) => ({ + target: nodes.indexOf(record.target), + added: [...record.addedNodes].map(node => nodes.indexOf(node)), + removed: [...record.removedNodes].map(node => nodes.indexOf(node)), + }); + const parentRecord = { + target: 0, + added: [width + 3, width + 4], + removed: [1, 2], + }; + expect(deepRecords.map(summarizeRecord)).toEqual([ + {target: firstChangedIndex + 1, added: [width + 1], removed: []}, + {target: secondChangedIndex + 1, added: [width + 2], removed: []}, + parentRecord, + ]); + expect(shallowRecords.map(summarizeRecord)).toEqual([parentRecord]); + + deepObserver.disconnect(); + shallowObserver.disconnect(); + root.destroy(); + }); + } + it('should report changes in different parts of the subtree as separate entries (subtree = true)', () => { const nodeRef = createRef();