Skip to content

Commit cf2e587

Browse files
rubennortefacebook-github-bot
authored andcommitted
Index MutationObserver child matching for wide lists (#60269)
Summary: ## 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
1 parent 25d13c9 commit cf2e587

2 files changed

Lines changed: 133 additions & 5 deletions

File tree

‎packages/react-native/ReactCommon/react/renderer/observers/mutation/MutationObserver.cpp‎

Lines changed: 34 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
#include "MutationObserver.h"
99
#include <react/renderer/core/ShadowNodeTraits.h>
1010
#include <react/renderer/uimanager/primitives.h>
11+
#include <unordered_map>
1112

1213
namespace facebook::react {
1314

@@ -150,12 +151,38 @@ void MutationObserver::recordMutationsInSubtrees(
150151
return;
151152
}
152153

154+
struct ChildMatch {
155+
size_t index;
156+
bool seenInOld{false};
157+
};
158+
const bool useIndex = oldChildren.size() >= 16 && newChildren.size() >= 16;
159+
std::unordered_map<const ShadowNodeFamily*, ChildMatch> newChildMatches;
160+
if (useIndex) {
161+
newChildMatches.reserve(newChildren.size());
162+
for (size_t i = 0; i < newChildren.size(); ++i) {
163+
newChildMatches.try_emplace(
164+
&newChildren[i]->getFamily(), ChildMatch{.index = i});
165+
}
166+
}
167+
168+
const auto findNewChild = [&](const ShadowNode& oldChild) {
169+
if (!useIndex) {
170+
return findNodeOfSameFamily(newChildren, oldChild);
171+
}
172+
const auto it = newChildMatches.find(&oldChild.getFamily());
173+
if (it == newChildMatches.end()) {
174+
return std::shared_ptr<const ShadowNode>{};
175+
}
176+
it->second.seenInOld = true;
177+
return newChildren[it->second.index];
178+
};
179+
153180
std::vector<std::shared_ptr<const ShadowNode>> addedNodes;
154181
std::vector<std::shared_ptr<const ShadowNode>> removedNodes;
155182

156183
// Check for removed nodes (and equal nodes for further inspection)
157-
for (auto& oldChild : oldChildren) {
158-
auto newChild = findNodeOfSameFamily(newChildren, *oldChild);
184+
for (const auto& oldChild : oldChildren) {
185+
const auto newChild = findNewChild(*oldChild);
159186
if (!newChild) {
160187
removedNodes.push_back(oldChild);
161188
} else if (observeSubtree) {
@@ -171,9 +198,11 @@ void MutationObserver::recordMutationsInSubtrees(
171198
}
172199

173200
// Check for added nodes
174-
for (auto& newChild : newChildren) {
175-
auto oldChild = findNodeOfSameFamily(oldChildren, *newChild);
176-
if (!oldChild) {
201+
for (const auto& newChild : newChildren) {
202+
const bool isAdded = useIndex
203+
? !newChildMatches.at(&newChild->getFamily()).seenInOld
204+
: !findNodeOfSameFamily(oldChildren, *newChild);
205+
if (isAdded) {
177206
addedNodes.push_back(newChild);
178207
}
179208
}

‎packages/react-native/src/private/webapis/mutationobserver/__tests__/MutationObserver-itest.js‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -406,6 +406,105 @@ describe('MutationObserver', () => {
406406
expect([...secondRecords[0].removedNodes]).toEqual([node111]);
407407
});
408408

409+
for (const width of [15, 16, 32]) {
410+
it(`should preserve record order when ${width} children are reordered and mutated`, () => {
411+
const root = Fantom.createRoot();
412+
const parentRef = createRef<HostInstance>();
413+
const firstChangedIndex = 4;
414+
const secondChangedIndex = 8;
415+
const childRefs = Array.from({length: width}, () =>
416+
createRef<HostInstance>(),
417+
);
418+
const firstDescendantRef = createRef<HostInstance>();
419+
const secondDescendantRef = createRef<HostInstance>();
420+
const firstAddedRef = createRef<HostInstance>();
421+
const secondAddedRef = createRef<HostInstance>();
422+
423+
Fantom.runTask(() => {
424+
root.render(
425+
<View ref={parentRef}>
426+
{childRefs.map((ref, i) => (
427+
<View key={i} ref={ref} />
428+
))}
429+
</View>,
430+
);
431+
});
432+
433+
const parent = nullthrows(parentRef.current);
434+
const originalChildren = childRefs.map(ref => nullthrows(ref.current));
435+
let deepRecords: ReadonlyArray<MutationRecordType> = [];
436+
let shallowRecords: ReadonlyArray<MutationRecordType> = [];
437+
const deepObserver = new MutationObserver(records => {
438+
deepRecords = records;
439+
});
440+
const shallowObserver = new MutationObserver(records => {
441+
shallowRecords = records;
442+
});
443+
deepObserver.observe(parent, {childList: true, subtree: true});
444+
deepObserver.observe(originalChildren[firstChangedIndex], {
445+
childList: true,
446+
});
447+
shallowObserver.observe(parent, {childList: true});
448+
449+
Fantom.runTask(() => {
450+
const updatedChildren = childRefs
451+
.slice(2)
452+
.map((ref, offset) => {
453+
const i = offset + 2;
454+
return (
455+
<View key={i} ref={ref}>
456+
{i === firstChangedIndex ? (
457+
<View ref={firstDescendantRef} />
458+
) : null}
459+
{i === secondChangedIndex ? (
460+
<View ref={secondDescendantRef} />
461+
) : null}
462+
</View>
463+
);
464+
})
465+
.reverse();
466+
root.render(
467+
<View ref={parentRef}>
468+
{[
469+
<View key="added-first" ref={firstAddedRef} />,
470+
...updatedChildren,
471+
<View key="added-second" ref={secondAddedRef} />,
472+
]}
473+
</View>,
474+
);
475+
});
476+
477+
const nodes: ReadonlyArray<unknown> = [
478+
parent,
479+
...originalChildren,
480+
nullthrows(firstDescendantRef.current),
481+
nullthrows(secondDescendantRef.current),
482+
nullthrows(firstAddedRef.current),
483+
nullthrows(secondAddedRef.current),
484+
];
485+
const summarizeRecord = (record: MutationRecordType) => ({
486+
target: nodes.indexOf(record.target),
487+
added: [...record.addedNodes].map(node => nodes.indexOf(node)),
488+
removed: [...record.removedNodes].map(node => nodes.indexOf(node)),
489+
});
490+
const parentRecord = {
491+
target: 0,
492+
added: [width + 3, width + 4],
493+
removed: [1, 2],
494+
};
495+
expect(deepRecords.map(summarizeRecord)).toEqual([
496+
{target: firstChangedIndex + 1, added: [width + 1], removed: []},
497+
{target: secondChangedIndex + 1, added: [width + 2], removed: []},
498+
parentRecord,
499+
]);
500+
expect(shallowRecords.map(summarizeRecord)).toEqual([parentRecord]);
501+
502+
deepObserver.disconnect();
503+
shallowObserver.disconnect();
504+
root.destroy();
505+
});
506+
}
507+
409508
it('should report changes in different parts of the subtree as separate entries (subtree = true)', () => {
410509
const nodeRef = createRef<HostInstance>();
411510

0 commit comments

Comments
 (0)