前端也需要算法:虚拟列表、diff 与调度
MrSmy Lv5

“前端不需要算法”这句话,在业务页面里勉强成立,但一碰到长列表、树形结构、实时更新的看板,就会立刻被打脸。

这篇不讲 LeetCode,讲三个天天在用但很少被当成算法问题的场景:虚拟列表、树 diff、任务调度。

场景一:1 万条数据的列表

最朴素的写法:

1
2
3
4
5
6
7
8
9
function List({ data }) {
return (
<div>
{data.map((item) => (
<Row key={item.id} item={item} />
))}
</div>
)
}

1 万条数据的结果:首次渲染 2.8 秒、内存 480MB、滚动掉帧到 8fps。

问题不在 React,在于 DOM 节点数量。1 万个 Row,每个 Row 内部 5 个节点 = 5 万个 DOM 节点。浏览器光是布局和绘制就撑不住。

虚拟列表的核心:只渲染”看得见的部分”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
function VirtualList({ items, itemHeight, height }) {
const [scrollTop, setScrollTop] = useState(0)

// 可见区域的起止索引
const startIndex = Math.floor(scrollTop / itemHeight)
const endIndex = Math.min(
items.length,
Math.ceil((scrollTop + height) / itemHeight) + 1, // +1 是缓冲
)

const visible = items.slice(startIndex, endIndex)

return (
<div
style={{ height, overflow: 'auto' }}
onScroll={(e) => setScrollTop(e.currentTarget.scrollTop)}
>
{/* 用占位撑开总高度,让滚动条正确 */}
<div style={{ height: items.length * itemHeight, position: 'relative' }}>
{visible.map((item, i) => (
<div
key={item.id}
style={{
position: 'absolute',
top: (startIndex + i) * itemHeight,
height: itemHeight,
}}
>
{item.name}
</div>
))}
</div>
</div>
)
}

效果对比(1 万条,固定行高 48px,容器 600px):

全量渲染 虚拟列表
渲染节点数 10000 约 14
首次渲染 2800ms 32ms
内存 480MB 38MB
滚动帧率 8fps 60fps

三个容易踩的坑

坑 1:滚动事件触发太频繁

onScroll 在滚动时每帧都可能触发,每次都 setState 会导致频繁重渲染。用 requestAnimationFrame 节流:

1
2
3
4
5
6
7
8
9
10
11
12
function useRafThrottle(fn) {
const ref = useRef({ ticking: false, lastArgs: null })
return useCallback((...args) => {
ref.current.lastArgs = args
if (ref.current.ticking) return
ref.current.ticking = true
requestAnimationFrame(() => {
fn(...ref.current.lastArgs)
ref.current.ticking = false
})
}, [fn])
}

坑 2:行高不固定

一旦某行内容换行,top: index * itemHeight 就全错了。两种解法:

  1. 强制固定高度(text-overflow: ellipsis),最省事
  2. 预估 + 实测修正:先按预估值排布,渲染后用 getBoundingClientRect 记录真实高度,维护一个前缀和数组
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 前缀和:offsets[i] = 前 i 行的总高度
const offsets = [0]
for (let i = 1; i <= items.length; i++) {
offsets[i] = offsets[i - 1] + (measured[i - 1] ?? estimatedHeight)
}

// 用二分查找定位 startIndex
function lowerBound(arr, target) {
let lo = 0
let hi = arr.length
while (lo < hi) {
const mid = (lo + hi) >> 1
if (arr[mid] < target) lo = mid + 1
else hi = mid
}
return Math.max(0, lo - 1)
}

这里才出现真正的算法:动态高度虚拟列表的本质是”前缀和 + 二分查找”。用线性扫描也能跑,但 1 万行时每次滚动扫 1 万次,白白多花 0.6ms。

坑 3:key 用 index

滚动时 visible 的 startIndex 一直在变,用 index 做 key 会导致 React 复用错节点(把第 1 条的内容塞进第 0 条的 DOM),出现滚动时文字闪烁。

场景二:树形结构的 diff

后台系统里”权限树”几乎是标配:3000 个节点,勾选一个父节点要联动所有子节点。

朴素的写法:

1
2
3
4
5
6
7
// 勾选父节点:递归找所有子节点
function checkAll(node, checked, tree) {
node.checked = checked
for (const child of node.children ?? []) {
checkAll(child, checked, tree)
}
}

单次操作 O(子树大小),看起来没问题。但”全选”要遍历所有节点,而每次勾选又要向上回算父节点状态:

1
2
3
4
5
6
7
8
9
10
// 向上回算:父节点是否全选/半选
function updateParent(nodeId, tree) {
const path = findPath(tree, nodeId) // O(N)
for (let i = path.length - 2; i >= 0; i--) {
const parent = path[i]
const children = parent.children ?? []
parent.checked = children.every((c) => c.checked)
parent.indeterminate = !parent.checked && children.some((c) => c.checked || c.indeterminate)
}
}

**问题在 findPath 是 O(N)**。3000 个节点、批量勾选 50 个 → 15 万次节点访问。实测卡顿 400ms。

优化:建索引 + 建父指针

1
2
3
4
5
6
7
8
9
10
11
12
13
function buildIndex(root) {
const byId = new Map()
const parentOf = new Map()

const walk = (node, parent) => {
byId.set(node.id, node)
if (parent) parentOf.set(node.id, parent.id)
for (const child of node.children ?? []) walk(child, node)
}
walk(root, null)

return { byId, parentOf }
}

有了 parentOf,向上回算变成 O(深度) 而不是 O(N):

1
2
3
4
5
6
7
8
9
10
function refreshUp(nodeId, { byId, parentOf }) {
let pid = parentOf.get(nodeId)
while (pid) {
const parent = byId.get(pid)
const children = parent.children ?? []
parent.checked = children.length > 0 && children.every((c) => c.checked)
parent.indeterminate = !parent.checked && children.some((c) => c.checked || c.indeterminate)
pid = parentOf.get(pid)
}
}

效果:单次勾选 400ms → 1.2ms(树深 6 层,3000 节点)。

这张表很能说明”数据结构 > 算法技巧”:

方案 单次操作 批量 50 次 结论
每次递归找路径 O(N) 200000 次访问 卡
建 parentOf 索引 O(depth) 300 次访问 流畅
只存扁平列表 O(1) 但失去树语义 — 不适用

代价是建索引要多 O(N) 的时间和一份额外内存,在 useMemo 里算一次就行。

场景三:diff 的本质是最长公共子序列

虚拟 DOM diff 常被讲成”React 的魔法”,其实核心是在 O(N) 的假设下退化 LCS。

标准 LCS(动态规划)是 O(N×M):

1
2
3
4
5
6
7
8
9
10
11
function lcs(a, b) {
const dp = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0))
for (let i = 1; i <= a.length; i++) {
for (let j = 1; j <= b.length; j++) {
dp[i][j] = a[i - 1] === b[j - 1]
? dp[i - 1][j - 1] + 1
: Math.max(dp[i - 1][j], dp[i][j - 1])
}
}
return dp[a.length][b.length]
}

1000 项 × 1000 项 = 100 万次操作,每次更新都跑一遍会卡死。所以框架都加了启发式假设:

假设 1:同层比较(只和同一父节点的子节点比),把树的 diff 降解成数组的 diff。

**假设 2:key 稳定时,只做”移动”而非”重建”**。React 的做法是:先用 map 记录旧节点的 index,遍历新列表查找(Map 查找 O(1)),再计算”是否需要移动”(用 lastPlacedIndex 的贪心策略,O(N))。

Vue 3 的双端比较更精巧:从两端同时向中间收缩,处理”头部插入/尾部追加”这类常见场景只要 O(变化量):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Vue 3 patchKeyedChildren 的骨架
let i = 0
let e1 = oldChildren.length - 1
let e2 = newChildren.length - 1

// 1. 从头同步相同前缀
while (i <= e1 && i <= e2 && same(oldChildren[i], newChildren[i])) {
patch(oldChildren[i], newChildren[i])
i++
}

// 2. 从尾同步相同后缀
while (i <= e1 && i <= e2 && same(oldChildren[e1], newChildren[e2])) {
patch(oldChildren[e1], newChildren[e2])
e1--
e2--
}

// 3. 处理剩余:旧的多 → 删除;新的多 → 新增;都有 → 求最长递增子序列决定最小移动

第 3 步求最长递增子序列(LIS),这是 Vue 3 性能优势的关键之一:它找出了”哪些节点不需要移动”,只移动其余节点。LIS 用 O(N log N) 的解法(耐心排序 + 二分 + 回溯索引)。

实测对比(1 万个带 key 的节点,中间插入 1 个):

方案 耗时
全量重建(无 key) 780ms
从前往后逐个比对 42ms
双端比较 0.8ms

这就是”知道算法”和”不知道”的实际差别——不是写不写得出快排,而是能不能看懂框架为什么这么实现,以及为什么”别用 index 当 key”。

场景四:调度——把任务切成小片

有个看板要一次性处理 5000 条数据(过滤 + 排序 + 聚合),同步算完要 800ms,页面白屏。

setTimeout(fn, 0) 切片也能做,但每个切片至少 4ms(嵌套 5 次后的浏览器下限),5000 条切 50 片 = 至少 200ms 的空转。

requestIdleCallback 是官方方案,但兼容性和”空闲时间可能永远不来”让它在低端机上不可靠(Safari 到 2021 年都还没实现)。

时间切片 + MessageChannel(React Scheduler 的做法):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
const channel = new MessageChannel()
let pendingCallback = null

channel.port1.onmessage = () => {
const cb = pendingCallback
pendingCallback = null
cb?.()
}

function scheduleTask(callback) {
pendingCallback = callback
channel.port2.postMessage(null) // 不受 4ms 限制
}

function timeSlice(items, work, onDone) {
let index = 0

const tick = () => {
const start = performance.now()
// 每片最多 5ms,剩下的让给浏览器渲染
while (index < items.length && performance.now() - start < 5) {
work(items[index], index)
index++
}

if (index < items.length) {
scheduleTask(tick)
} else {
onDone()
}
}

scheduleTask(tick)
}

为什么是 MessageChannel 而不是 setTimeout:setTimeout 有最小延迟(嵌套后 4ms),而 postMessage 是宏任务但没有延迟下限,能塞进每一帧的空隙。

实测:

方案 总耗时 首帧可交互
同步处理 800ms 800ms
setTimeout 切片 1180ms 90ms
MessageChannel 切片 870ms 45ms

总耗时反而更长(因为切片有开销、渲染被打断),但首帧可交互时间从 800ms 降到 45ms —— 这就是”牺牲吞吐换响应”的典型权衡。

什么时候不值得优化

写到这里必须补一句:上面这些都建立在”数据量真的到这个量级”之上。

我们踩过反向的坑:一个只有 200 条数据的列表,被套上了虚拟列表,结果:

  • 代码从 40 行变成 300 行
  • 每次加功能都要考虑”虚拟列表支不支持”
  • 搜索框做”滚动到匹配项”花了 2 天
  • 200 条数据直接全量渲染只要 12ms,根本不需要优化

判断标准:

数据量 建议
< 500 条 直接渲染,别优化
500 - 2000 先做分页,不够再虚拟化
> 2000 虚拟列表(优先固定行高)
> 1 万 + 实时更新 虚拟列表 + 增量 diff + 时间切片

小结

前端用到的算法不复杂,但很”具体”:

  1. 虚拟列表 = 区间计算(除法) + 动态高度时的前缀和 + 二分查找
  2. 树形联动 = 用空间换时间(建 parentOf 索引),把 O(N) 降到 O(深度)
  3. diff = LCS 的退化版本 + 启发式假设(同层、key 稳定)+ LIS 求最小移动
  4. 调度 = 把长任务切成 < 5ms 的片,用 MessageChannel 而不是 setTimeout

真正重要的是判断力:先量数据量,再选方案。过度优化带来的复杂度,往往比性能问题本身更贵。

  • 本文标题:前端也需要算法:虚拟列表、diff 与调度
  • 本文作者:MrSmy
  • 创建时间:2021-02-28 21:12:00
  • 本文链接:https://fengyang.live/2021/02/28/前端也需要算法:虚拟列表、diff与调度/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!