示例工程 19-dom-events
19-dom-events/05-binding-cost/index.html
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>19 · 直接绑定 vs 事件委托</title>
<style>
button { margin: 1px; }
</style>
</head>
<body>
<p>两组各 1000 个按钮,测量初始化耗时。</p>
<div id="direct"></div>
<div id="delegated"></div>
<script type="module">
import { run } from './main.js';
const N = 1000;
const noop = () => {};
function build(container) {
const frag = document.createDocumentFragment();
for (let i = 0; i < N; i++) {
const b = document.createElement('button');
b.textContent = String(i);
frag.appendChild(b);
}
container.appendChild(frag);
return [...container.children];
}
const directButtons = build(document.getElementById('direct'));
const delegatedButtons = build(document.getElementById('delegated'));
const t0 = performance.now();
directButtons.forEach((button) => button.addEventListener('click', noop));
const directMs = performance.now() - t0;
const t1 = performance.now();
let delegatedCalls = 0;
document.getElementById('delegated').addEventListener('click', () => {
delegatedCalls += 1;
});
const delegatedMs = performance.now() - t1;
delegatedButtons[500].click();
console.log('直接绑定耗时 =>', directMs.toFixed(2), 'ms');
console.log('委托绑定耗时 =>', delegatedMs.toFixed(2), 'ms');
console.log('委托点击命中次数 =>', delegatedCalls);
run();
</script>
</body>
</html>