perf(jsx/dom): reduce lookup work for large keyed updates (#5340)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* test(jsx/dom): cover child reconciliation semantics Lock down DOM identity, retained component state, duplicate-key matching, unkeyed reuse and cleanup order before changing reconciliation. * perf(jsx/dom): index expensive keyed child reconciliation Keep forward scans for cheap updates and try a key index once accumulated search work exceeds a linear budget. Preserve matching and removal order: reject duplicate old keys, allow one undefined key, retain strict key comparison, distinguish text nodes, and return to array matching for unkeyed elements. Cover linear lookup work, common updates, mixed text and element transitions, previous-child restoration, retained state and cleanup order. Array shifts and duplicate-key or unkeyed fallback paths remain unchanged. * test(jsx/dom): add keyed reconciliation benchmark Measure build-only updates for same-order lists, second-child removal, adjacent swaps, reversal and reversal with an unkeyed footer at three list sizes. Exclude JSX creation and DOM work, use short batches with fresh nodes, report the median batch time, and verify child identity.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+707 added−2 removed
- tests:+601 added−0 removed
- other:+106 added−2 removed
Provenance
- Commit
7792f5d- Tree
52b23ab- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
e7b38ee
3 files changed+707 added−2 removed
added:benchmarks/jsx-dom/benchmark.ts+65 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465// Run from the repository root: bun benchmarks/jsx-dom/benchmark.ts// Measures build() only, excluding JSX creation and DOM updates.import { jsx } from '../../src/jsx/dom/jsx-runtime'import type { NodeObject } from '../../src/jsx/dom/render'import { build, buildNode } from '../../src/jsx/dom/render'
for (const size of [100, 1000, 5000]) { for (const kind of [ 'same-order', 'remove-second', 'adjacent-swap', 'reverse', 'reverse-unkeyed-footer', ]) { const ids = Array.from({ length: size }, (_, i) => i) const hasFooter = kind === 'reverse-unkeyed-footer' const createChildren = (ids: number[]) => { const children = ids.map((id) => jsx('p', {}, String(id))) if (hasFooter) { children.push(jsx('p', {})) } return children } const nextIds = [...ids] if (kind === 'remove-second') { nextIds.splice(1, 1) } else if (kind === 'adjacent-swap') { ;[nextIds[1], nextIds[2]] = [nextIds[2], nextIds[1]] } else if (kind.startsWith('reverse')) { nextIds.reverse() } const samples: number[] = [] // Use fresh nodes in short batches instead of mixing long-lived node states. for (let batch = 0; batch < 5; batch++) { const parent = buildNode(jsx('div', { children: createChildren(ids) })) as NodeObject build([], parent) const initialChildren = parent.vC const update = (children: ReturnType<typeof createChildren>) => { parent.vC = initialChildren parent.props.children = children build([], parent) } for (let i = 0; i < 10; i++) { update(createChildren(nextIds)) } const inputs = Array.from({ length: 20 }, () => createChildren(nextIds)) const start = performance.now() for (const children of inputs) { update(children) } samples.push((performance.now() - start) / inputs.length) if ( parent.vC.length !== nextIds.length + Number(hasFooter) || parent.vC.some( (child, i) => child !== initialChildren[i < nextIds.length ? nextIds[i] : size] ) ) { throw new Error('Unexpected child identity after update') } } samples.sort((a, b) => a - b) const ms = samples[Math.floor(samples.length / 2)] console.log(`${kind}, ${size} keyed children: ${ms.toFixed(3)} ms/build (median)`) }}modified:src/jsx/dom/index.test.tsx+601 added
13 unmodified lines14 useMemo,15 useRef,16 useState,17 } from '../hooks'18+import type { NodeObject } from './render'19+import { build, buildNode } from './render'20 import DefaultExport, {21 cloneElement,22 cloneElement as cloneElementForDom,23 createElement as createElementForDom,113 unmodified lines137 expect(root.innerHTML).toBe(138 Array.from({ length: 1000 }, (_, i) => `<div><span>${i}</span></div>`).join('')139 )140 })141+142+ it.each(['same-order', 'remove-second', 'adjacent-swap'])(143+ 'preserves keyed children during common updates: %s',144+ (kind) => {145+ const size = 100146+ const ids = Array.from({ length: size }, (_, i) => i)147+ const createRow = (id: number) => <div key={id}>{id}</div>148+ const parent = buildNode(<section>{ids.map(createRow)}</section>) as NodeObject149+ build([], parent)150+ const initialChildren = parent.vC151+ const nextIds = [...ids]152+ if (kind === 'remove-second') {153+ nextIds.splice(1, 1)154+ } else if (kind === 'adjacent-swap') {155+ ;[nextIds[1], nextIds[2]] = [nextIds[2], nextIds[1]]156+ }157+ parent.props.children = [[], ...nextIds.map(createRow)]158+159+ build([], parent)160+161+ expect(parent.vC).toHaveLength(nextIds.length)162+ nextIds.forEach((id, i) => expect(parent.vC[i]).toBe(initialChildren[id]))163+ expect(parent.vR).toHaveLength(kind === 'remove-second' ? 1 : 0)164+ if (kind === 'remove-second') {165+ expect(parent.vR[0]).toBe(initialChildren[1])166+ }167+ }168+ )169 })170 171+ describe('large keyed updates', () => {172+ it.each([173+ 'reverse',174+ 'rotate-half',175+ 'replace-all',176+ 'footer-unkeyed',177+ 'footer-text',178+ 'insert-text',179+ 'move-text',180+ ])('matches keyed list updates in linear work: %s', (kind) => {181+ const measure = (size: number) => {182+ let oldKeyReads = 0183+ let newKeyReads = 0184+ const createRow = (id: number, old = false) => {185+ const row = <div>{id}</div>186+ // Count both sides so node normalization cannot silently disable the check.187+ Object.defineProperty(row, 'key', {188+ configurable: true,189+ get: () => {190+ if (old) {191+ oldKeyReads++192+ } else {193+ newKeyReads++194+ }195+ return id196+ },197+ })198+ return row199+ }200+ const ids = Array.from({ length: size }, (_, i) => i)201+ const before: Child[] = ids.map((id) => createRow(id, true))202+ if (kind === 'footer-unkeyed') {203+ before.push(<div>footer</div>)204+ } else if (kind === 'footer-text' || kind === 'move-text') {205+ before.push('original')206+ }207+ const parent = buildNode(<section>{before}</section>) as NodeObject208+ build([], parent)209+ const initial = parent.vC210+ const next = [...ids]211+ if (kind === 'rotate-half') {212+ next.push(...next.splice(0, size / 2))213+ } else if (kind === 'replace-all') {214+ next.splice(0, size, ...ids.map((id) => id + size))215+ } else {216+ next.reverse()217+ }218+ const after: Child[] = next.map((id) => createRow(id))219+ const expected = next.map((id) => (id < size ? initial[id] : undefined))220+ if (kind === 'footer-unkeyed' || kind === 'footer-text') {221+ after.push(kind === 'footer-unkeyed' ? <div>footer</div> : 'updated')222+ expected.push(initial[size])223+ } else if (kind === 'insert-text' || kind === 'move-text') {224+ after.splice(4, 0, 'updated')225+ expected.splice(4, 0, kind === 'move-text' ? initial[size] : undefined)226+ if (kind === 'move-text') {227+ after.splice(8, 0, 'extra')228+ expected.splice(8, 0, undefined)229+ }230+ }231+ parent.props.children = after232+ oldKeyReads = newKeyReads = 0233+ build([], parent)234+ const reads = { old: oldKeyReads, new: newKeyReads }235+236+ expect(parent.vC).toHaveLength(expected.length)237+ expected.forEach((child, i) => {238+ if (child) {239+ expect(parent.vC[i]).toBe(child)240+ } else {241+ expect(initial.includes(parent.vC[i])).toBe(false)242+ }243+ })244+ if (kind === 'footer-text' || kind === 'insert-text' || kind === 'move-text') {245+ expect(parent.vC[kind === 'footer-text' ? size : 4]).toMatchObject({ t: 'updated' })246+ }247+ if (kind === 'move-text') {248+ expect(parent.vC[8]).toMatchObject({ t: 'extra' })249+ }250+ expect(parent.vR).toHaveLength(kind === 'replace-all' ? size : 0)251+ parent.vR.forEach((child, i) => expect(child).toBe(initial[i]))252+ return reads253+ }254+255+ const small = measure(64)256+ const large = measure(128)257+ expect(small.old).toBeGreaterThan(0)258+ expect(small.new).toBeGreaterThan(0)259+ expect(large.old).toBeLessThan(small.old * 3)260+ expect(large.old + large.new).toBeLessThan((small.old + small.new) * 3)261+ })262+263+ it.each(['unkeyed-to-text', 'undefined-tag-to-text', 'text-to-unkeyed'])(264+ 'replaces incompatible children after indexing: %s',265+ (kind) => {266+ const ids = Array.from({ length: 40 }, (_, i) => i)267+ const createRow = (id: number) => <div key={id}>{id}</div>268+ let footer: Child = kind === 'text-to-unkeyed' ? 'original' : <span>footer</span>269+ if (kind === 'undefined-tag-to-text') {270+ // @ts-expect-error An undefined component still creates a NodeObject at runtime.271+ footer = createElementForDom(undefined, {})272+ }273+ const parent = buildNode(<section>{[...ids.map(createRow), footer]}</section>) as NodeObject274+ build([], parent)275+ const initial = parent.vC276+ const next = [...ids].reverse()277+ const after: Child[] = next.map(createRow)278+ // Consume an indexed child before replacing the incompatible footer.279+ after.splice(4, 0, kind === 'text-to-unkeyed' ? <span>updated</span> : 'updated')280+ parent.props.children = after281+282+ build([], parent)283+284+ expect(parent.vC).toHaveLength(ids.length + 1)285+ next.forEach((id, i) => expect(parent.vC[i < 4 ? i : i + 1]).toBe(initial[id]))286+ expect(initial.includes(parent.vC[4])).toBe(false)287+ expect(parent.vC[4]).toMatchObject(288+ kind === 'text-to-unkeyed' ? { tag: 'span' } : { t: 'updated', d: true }289+ )290+ expect(parent.vR).toHaveLength(1)291+ expect(parent.vR[0]).toBe(initial[ids.length])292+ }293+ )294+295+ it('restores previous children with indexed matching and ordered removals', () => {296+ const ids = Array.from({ length: 40 }, (_, i) => i)297+ const createRow = (id: number) => <div key={id}>{id}</div>298+ const parent = buildNode(<section>{ids.map(createRow)}</section>) as NodeObject299+ build([], parent)300+ const initial = parent.vC301+ let keyReads = 0302+ initial.forEach((child, id) => {303+ Object.defineProperty(child, 'key', {304+ configurable: true,305+ get: () => {306+ keyReads++307+ return id308+ },309+ })310+ })311+312+ // Explicit fallback children preserve the original list in pC.313+ build([], parent, [<span>Loading</span>])314+ const fallback = parent.vC315+ expect(parent.pC).toBe(initial)316+ const next = [...ids].reverse().filter((id) => id !== 10 && id !== 20)317+ parent.props.children = next.map(createRow)318+ keyReads = 0319+ build([], parent)320+ const matchingReads = keyReads321+322+ expect(matchingReads).toBeGreaterThan(0)323+ expect(matchingReads).toBeLessThan(ids.length * 8)324+ expect(parent.vC).toHaveLength(next.length)325+ next.forEach((id, i) => expect(parent.vC[i]).toBe(initial[id]))326+ const removed = [...fallback, initial[10], initial[20]]327+ expect(parent.vR).toHaveLength(removed.length)328+ removed.forEach((child, i) => expect(parent.vR[i]).toBe(child))329+ expect(parent.pC).toBeUndefined()330+ })331+332+ it.each([333+ { name: 'duplicate old keys', oldKeys: [0, 0], newKeys: [0, 0], matches: [0, 1] },334+ { name: 'an unkeyed old child', oldKeys: [undefined, 1], newKeys: [undefined], matches: [0] },335+ {336+ name: 'multiple unkeyed old children',337+ oldKeys: [undefined, undefined],338+ newKeys: [undefined, undefined],339+ matches: [0, 1],340+ },341+ { name: 'NaN keys', oldKeys: [NaN, 1], newKeys: [NaN, 1], matches: [-1, 1] },342+ {343+ name: 'a different tag for the same key',344+ oldKeys: [0, 1],345+ newKeys: [0, 0],346+ firstNewTag: 'span',347+ matches: [-1, 0],348+ },349+ { name: 'a repeated new key', oldKeys: [0, 1], newKeys: [0, 0], matches: [0, -1] },350+ {351+ name: 'different old tags sharing a key',352+ oldKeys: [0, 0],353+ oldSecondTag: 'span',354+ newKeys: [0, 0],355+ firstNewTag: 'span',356+ matches: [1, 0],357+ },358+ ])(359+ 'preserves matching and removal order with $name',360+ ({ oldKeys, newKeys, matches, oldSecondTag, firstNewTag }) => {361+ const before = Array.from({ length: 40 }, (_, i) =>362+ createElement(i === 1 ? oldSecondTag || 'div' : 'div', {363+ key: i < oldKeys.length ? oldKeys[i] : i,364+ })365+ )366+ const parent = buildNode(<section>{before}</section>) as NodeObject367+ build([], parent)368+ const initial = parent.vC369+ // This prefix exceeds the scan budget and attempts to index the remaining nodes.370+ const prefix = [39, 38, 37, 36]371+ parent.props.children = [372+ ...prefix.map((key) => <div key={key} />),373+ ...newKeys.map((key, i) =>374+ createElement(i === 0 ? firstNewTag || 'div' : 'div', { key })375+ ),376+ ]377+ build([], parent)378+379+ const expected = [...prefix, ...matches]380+ expect(parent.vC).toHaveLength(expected.length)381+ expected.forEach((oldIndex, i) => {382+ if (oldIndex === -1) {383+ expect(initial.includes(parent.vC[i])).toBe(false)384+ } else {385+ expect(parent.vC[i]).toBe(initial[oldIndex])386+ }387+ })388+ const removed = initial.filter((_, i) => !expected.includes(i))389+ expect(parent.vR).toHaveLength(removed.length)390+ removed.forEach((child, i) => expect(parent.vR[i]).toBe(child))391+ }392+ )393+394+ it.each(['keyed', 'unkeyed', 'text'])(395+ 'preserves state and cleanup order after indexing followed by %s children',396+ async (kind) => {397+ let update: () => void = () => {}398+ const cleaned: number[] = []399+ const Row = ({ id }: { id: number }) => {400+ const [initialId] = useState(id)401+ const [count, setCount] = useState(0)402+ useLayoutEffect(403+ () => () => {404+ cleaned.push(initialId)405+ },406+ []407+ )408+ return (409+ <button onClick={() => setCount(count + 1)}>410+ {id}:{initialId}:{count}411+ </button>412+ )413+ }414+ const before = Array.from({ length: 40 }, (_, i) => i)415+ const after = [...before]416+ .reverse()417+ .filter((id) => id !== 10 && id !== 20 && (kind !== 'unkeyed' || id !== 0))418+ // Consume an indexed child before introducing an unkeyed or text child.419+ if (kind !== 'keyed') {420+ after.splice(4, 0, kind === 'unkeyed' ? 100 : 101)421+ }422+ const App = () => {423+ const [ids, setIds] = useState(before)424+ update = () => setIds(after)425+ return ids.map((id) =>426+ id === 101 ? 'inserted' : <Row key={id === 100 ? undefined : id} id={id} />427+ )428+ }429+430+ render(<App />, root)431+ const initial = [...root.querySelectorAll('button')]432+ initial[0].click()433+ await Promise.resolve()434+ update()435+ await Promise.resolve()436+437+ const rows = after.filter((id) => id !== 101)438+ expect(root.children).toHaveLength(rows.length)439+ rows.forEach((id, i) => {440+ const oldId = id === 100 ? 0 : id441+ expect(root.children[i]).toBe(initial[oldId])442+ expect(root.children[i].textContent).toBe(`${id}:${oldId}:${oldId === 0 ? 1 : 0}`)443+ })444+ if (kind === 'text') {445+ expect(root.childNodes[4].textContent).toBe('inserted')446+ }447+ expect(cleaned).toEqual([10, 20])448+ }449+ )450+ })451+452 describe('attribute', () => {453 it('simple', () => {454 const App = () => <div id='app' class='app' />455 render(<App />, root)1561 unmodified lines2017 '<div><div>a</div><div>c</div><div>b</div><button>add</button><button>remove</button><button>swap</button></div>'2018 )2019 })2020 2021+ it('preserves keyed child identity and state when reordering', async () => {2022+ let reverse: () => void = () => {}2023+ const Row = ({ id }: { id: string }) => {2024+ const [count, setCount] = useState(0)2025+ return (2026+ <button data-id={id} onClick={() => setCount(count + 1)}>2027+ {id}:{count}2028+ </button>2029+ )2030+ }2031+ const App = () => {2032+ const [ids, setIds] = useState(['a', 'b', 'c'])2033+ reverse = () => setIds((ids) => [...ids].reverse())2034+ return ids.map((id) => <Row key={id} id={id} />)2035+ }2036+2037+ render(<App />, root)2038+ const initialRows = Object.fromEntries(2039+ [...root.querySelectorAll<HTMLButtonElement>('button')].map((element) => [2040+ element.dataset.id,2041+ element,2042+ ])2043+ )2044+2045+ initialRows.b.click()2046+ await Promise.resolve()2047+ reverse()2048+ await Promise.resolve()2049+2050+ const reorderedRows = [...root.querySelectorAll<HTMLButtonElement>('button')]2051+ expect(reorderedRows.map((element) => element.textContent)).toEqual(['c:0', 'b:1', 'a:0'])2052+ expect(reorderedRows[0]).toBe(initialRows.c)2053+ expect(reorderedRows[1]).toBe(initialRows.b)2054+ expect(reorderedRows[2]).toBe(initialRows.a)2055+ })2056+2057+ it('reuses duplicate keyed children in their previous order', async () => {2058+ let rotate: () => void = () => {}2059+ const Row = ({ label }: { label: string }) => {2060+ const [initialLabel] = useState(label)2061+ return <div>{`${label}:${initialLabel}`}</div>2062+ }2063+ const App = () => {2064+ const [labels, setLabels] = useState(['other', 'first', 'second'])2065+ rotate = () => setLabels(['first', 'second', 'other'])2066+ return labels.map((label) => (2067+ <Row key={label === 'other' ? 'other' : 'duplicate'} label={label} />2068+ ))2069+ }2070+2071+ render(<App />, root)2072+ const initialRows = [...root.querySelectorAll('div')]2073+ rotate()2074+ await Promise.resolve()2075+2076+ const reorderedRows = [...root.querySelectorAll('div')]2077+ expect(reorderedRows.map((element) => element.textContent)).toEqual([2078+ 'first:first',2079+ 'second:second',2080+ 'other:other',2081+ ])2082+ expect(reorderedRows[0]).toBe(initialRows[1])2083+ expect(reorderedRows[1]).toBe(initialRows[2])2084+ expect(reorderedRows[2]).toBe(initialRows[0])2085+ })2086+2087+ it.each([2088+ {2089+ consumedBy: 'an earlier keyed child',2090+ before: [2, 1, 5, 1],2091+ after: [9, 2, 1, 1],2092+ matches: [-1, 0, 1, 3],2093+ statefulIndex: 3,2094+ removedIndices: [2],2095+ },2096+ {2097+ consumedBy: 'an earlier unkeyed child',2098+ before: ['other', 1, 1, 1, 3],2099+ after: [1, undefined, 1, 1],2100+ matches: [1, 2, 3, -1],2101+ statefulIndex: 2,2102+ removedIndices: [0, 4],2103+ },2104+ ])(2105+ 'does not reuse children already consumed by $consumedBy',2106+ async ({ before, after, matches, statefulIndex, removedIndices }) => {2107+ let reorder: () => void = () => {}2108+ const Other = () => <button>Other</button>2109+ const Row = () => {2110+ const [count, setCount] = useState(0)2111+ return <button onClick={() => setCount(count + 1)}>{count}</button>2112+ }2113+ const App = () => {2114+ const [keys, setKeys] = useState<Array<number | string | undefined>>(before)2115+ reorder = () => setKeys(after)2116+ return keys.map((key) => (key === 'other' ? <Other /> : <Row key={key} />))2117+ }2118+2119+ render(<App />, root)2120+ const initialRows = [...root.querySelectorAll('button')]2121+ initialRows[statefulIndex].click()2122+ await Promise.resolve()2123+ reorder()2124+ await Promise.resolve()2125+2126+ const reorderedRows = [...root.querySelectorAll('button')]2127+ expect(reorderedRows).toHaveLength(matches.length)2128+ matches.forEach((oldIndex, newIndex) => {2129+ if (oldIndex === -1) {2130+ expect(initialRows.includes(reorderedRows[newIndex])).toBe(false)2131+ } else {2132+ expect(reorderedRows[newIndex]).toBe(initialRows[oldIndex])2133+ }2134+ expect(reorderedRows[newIndex].textContent).toBe(oldIndex === statefulIndex ? '1' : '0')2135+ })2136+ removedIndices.forEach((index) => {2137+ expect(initialRows[index].isConnected).toBe(false)2138+ })2139+ }2140+ )2141+2142+ it('preserves existing keyed children when prepending', async () => {2143+ let prepend: () => void = () => {}2144+ const App = () => {2145+ const [ids, setIds] = useState(['a', 'b'])2146+ prepend = () => setIds(['x', 'a', 'b'])2147+ return ids.map((id) => <div key={id}>{id}</div>)2148+ }2149+2150+ render(<App />, root)2151+ const initialRows = [...root.querySelectorAll('div')]2152+ prepend()2153+ await Promise.resolve()2154+2155+ const prependedRows = [...root.querySelectorAll('div')]2156+ expect(prependedRows.map((element) => element.textContent)).toEqual(['x', 'a', 'b'])2157+ expect(prependedRows[1]).toBe(initialRows[0])2158+ expect(prependedRows[2]).toBe(initialRows[1])2159+ })2160+2161+ it('unmounts a keyed child removed from the middle', async () => {2162+ let removeMiddle: () => void = () => {}2163+ const cleanup = vi.fn()2164+ const ref = vi.fn().mockReturnValue(cleanup)2165+ const App = () => {2166+ const [ids, setIds] = useState(['a', 'b', 'c'])2167+ removeMiddle = () => setIds(['a', 'c'])2168+ return ids.map((id) => (2169+ <div key={id} ref={id === 'b' ? ref : undefined}>2170+ {id}2171+ </div>2172+ ))2173+ }2174+2175+ render(<App />, root)2176+ const initialRows = [...root.querySelectorAll('div')]2177+ removeMiddle()2178+ await Promise.resolve()2179+2180+ const remainingRows = [...root.querySelectorAll('div')]2181+ expect(remainingRows.map((element) => element.textContent)).toEqual(['a', 'c'])2182+ expect(remainingRows[0]).toBe(initialRows[0])2183+ expect(remainingRows[1]).toBe(initialRows[2])2184+ expect(initialRows[1].isConnected).toBe(false)2185+ expect(cleanup).toHaveBeenCalledOnce()2186+ })2187+2188+ it('cleans up removed keyed children in their previous order', async () => {2189+ let remove: () => void = () => {}2190+ const cleanedUp: string[] = []2191+ const Row = ({ id }: { id: string }) => {2192+ useLayoutEffect(2193+ () => () => {2194+ cleanedUp.push(id)2195+ },2196+ []2197+ )2198+ return <div>{id}</div>2199+ }2200+ const App = () => {2201+ const [ids, setIds] = useState(['a', 'b', 'c', 'd'])2202+ remove = () => setIds(['b'])2203+ return ids.map((id) => <Row key={id} id={id} />)2204+ }2205+2206+ render(<App />, root)2207+ const initialRows = [...root.children]2208+ remove()2209+ await Promise.resolve()2210+2211+ expect(root.children).toHaveLength(1)2212+ expect(root.firstElementChild).toBe(initialRows[1])2213+ expect(cleanedUp).toEqual(['a', 'c', 'd'])2214+ expect(initialRows.filter((row) => row.isConnected)).toHaveLength(1)2215+ })2216+2217+ it('allows an unkeyed child to reuse a keyed child with the same tag', async () => {2218+ let removeKeyedSiblings: () => void = () => {}2219+ const Row = ({ label }: { label: string }) => {2220+ const [initialLabel] = useState(label)2221+ return <div>{`${label}:${initialLabel}`}</div>2222+ }2223+ const App = () => {2224+ const [showSingle, setShowSingle] = useState(false)2225+ removeKeyedSiblings = () => setShowSingle(true)2226+ return showSingle ? (2227+ <Row label='replacement' />2228+ ) : (2229+ [<Row key='keyed' label='keyed' />, <Row label='unkeyed' />]2230+ )2231+ }2232+2233+ render(<App />, root)2234+ const initialRows = [...root.querySelectorAll('div')]2235+ removeKeyedSiblings()2236+ await Promise.resolve()2237+2238+ const replacement = root.querySelector('div') as HTMLDivElement2239+ expect(replacement.textContent).toBe('replacement:keyed')2240+ expect(replacement).toBe(initialRows[0])2241+ expect(initialRows[1].isConnected).toBe(false)2242+ })2243+2244+ it('preserves unkeyed elements and text when removing a leading sibling', async () => {2245+ let hideHeading: () => void = () => {}2246+ const App = () => {2247+ const [showHeading, setShowHeading] = useState(true)2248+ hideHeading = () => setShowHeading(false)2249+ return [2250+ showHeading && <h2>Heading</h2>,2251+ <p>First paragraph</p>,2252+ 'First text',2253+ <span>First span</span>,2254+ <p>Second paragraph</p>,2255+ 'Second text',2256+ <span>Second span</span>,2257+ ]2258+ }2259+2260+ render(<App />, root)2261+ const initialNodes = [...root.childNodes]2262+ hideHeading()2263+ await Promise.resolve()2264+2265+ expect(root.childNodes).toHaveLength(initialNodes.length - 1)2266+ initialNodes.slice(1).forEach((node, i) => {2267+ expect(root.childNodes[i]).toBe(node)2268+ })2269+ expect(initialNodes[0].isConnected).toBe(false)2270+ })2271+2272+ it('resumes unkeyed matching after a keyed sibling consumes the next candidate', async () => {2273+ let reorder: () => void = () => {}2274+ const App = () => {2275+ const [updated, setUpdated] = useState(false)2276+ reorder = () => setUpdated(true)2277+ return updated2278+ ? [<p>A</p>, <p key='b'>B</p>, <p>C</p>, <p>D</p>, <span>X</span>, <span>Y</span>]2279+ : [<h2>Heading</h2>, <p key='a'>A</p>, <p key='b'>B</p>, <p>C</p>]2280+ }2281+2282+ render(<App />, root)2283+ const initialNodes = [...root.children]2284+ reorder()2285+ await Promise.resolve()2286+2287+ expect(root.innerHTML).toBe('<p>A</p><p>B</p><p>C</p><p>D</p><span>X</span><span>Y</span>')2288+ initialNodes.slice(1).forEach((node, i) => {2289+ expect(root.children[i]).toBe(node)2290+ })2291+ expect(initialNodes[0].isConnected).toBe(false)2292+ })2293+2294+ it('does not reuse children with NaN keys', async () => {2295+ let rerender: () => void = () => {}2296+ const App = () => {2297+ const [count, setCount] = useState(0)2298+ rerender = () => setCount((count) => count + 1)2299+ return <div key={Number.NaN}>{count}</div>2300+ }2301+2302+ render(<App />, root)2303+ const initialChild = root.firstElementChild2304+ rerender()2305+ await Promise.resolve()2306+2307+ expect(root.textContent).toBe('1')2308+ expect(root.firstElementChild).not.toBe(initialChild)2309+ })2310+2311 it('swap deferent type of child component', async () => {2312 const Even = () => <p>Even</p>2313 const Odd = () => <div>Odd</div>2314 const Counter = () => {1314 unmodified linesmodified:src/jsx/dom/render.ts+41 added-2 removed
490 unmodified lines491 oldContexts.length === newContexts.length &&492 oldContexts.every((ctx, i) => ctx[1] === newContexts[i][1])493 )494 495+const indexChildrenByKey = (children: Node[]): Map<unknown, Node> | undefined => {496+ const index = new Map<unknown, Node>()497+ // Insert in the original order so map iteration preserves removal order.498+ for (const child of children) {499+ const key = child.key500+ if (index.has(key)) {501+ return502+ }503+ index.set(key, child)504+ }505+ return index506+}507+508 const fallbackUpdateFnArrayMap: WeakMap<509 NodeObject,510 Array<() => Promise<NodeObject | undefined>>511 > = new WeakMap<NodeObject, Array<() => Promise<NodeObject | undefined>>>()12 unmodified lines524 // eslint-disable-next-line @typescript-eslint/no-explicit-any525 foundErrorHandler = (children[0] as any)[DOM_ERROR_HANDLER] as ErrorHandler526 context[5]!.push([context, foundErrorHandler, node])527 }515- const oldVChildren: Node[] | undefined = buildWithPreviousChildren528+ let oldVChildren: Node[] | undefined = buildWithPreviousChildren529 ? [...(node.pC as Node[])]530 : node.vC531 ? [...node.vC]532 : undefined533 const vChildren: Node[] = []534 let prevNode: Node | undefined535+ let scanBudget = (oldVChildren?.length || 0) * 2536+ let oldChildrenByKey: Map<unknown, Node> | undefined537 for (let i = 0; i < children.length; i++) {538 if (Array.isArray(children[i])) {539 children.splice(i, 1, ...((children[i] as unknown[]).flat(Infinity) as Child[]))540 i--14 unmodified lines555 }556 }557 558 let oldChild: NodeObject | undefined559+ if (oldChildrenByKey && child.key === undefined && !isNodeString(child)) {560+ oldVChildren = [...oldChildrenByKey.values()]561+ oldChildrenByKey = undefined562+ }563+ if (oldChildrenByKey) {564+ const key = child.key565+ const candidate = oldChildrenByKey.get(key)566+ // The strict check also preserves the existing behavior for NaN keys.567+ if (568+ candidate &&569+ (isNodeString(child)570+ ? isNodeString(candidate)571+ : candidate.tag === child.tag && candidate.key === key)572+ ) {573+ oldChild = candidate as NodeObject574+ oldChildrenByKey.delete(key)575+ }544- if (oldVChildren && oldVChildren.length) {576+ } else if (oldVChildren && oldVChildren.length) {577 const i = oldVChildren.findIndex(578 isNodeString(child)579 ? (c) => isNodeString(c)580 : child.key !== undefined581 ? (c) => c.key === (child as Node).key && c.tag === (child as Node).tag582 : (c) => c.tag === (child as Node).tag583 )584 585+ scanBudget -= i === -1 ? oldVChildren.length : i586 if (i !== -1) {587 oldChild = oldVChildren[i] as NodeObject588 oldVChildren.splice(i, 1)589 }590+ // Try indexing once, after searches exceed a linear budget.591+ if (scanBudget < 0) {592+ scanBudget = Infinity593+ oldChildrenByKey = indexChildrenByKey(oldVChildren)594+ }595 }596 597 if (oldChild) {598 if (isNodeString(child)) {42 unmodified lines641 }642 prevNode = child643 }644 }645+ oldVChildren = oldChildrenByKey ? [...oldChildrenByKey.values()] : oldVChildren646 node.vR = buildWithPreviousChildren ? [...node.vC, ...(oldVChildren || [])] : oldVChildren || []647 node.vC = vChildren648 if (buildWithPreviousChildren) {649 delete node.pC217 unmodified lines