Performance API 提供高精度时间测量,优于 Date.now(),可用于精准分析代码执行性能。使用 performance.now() 可测量小段代码耗时;通过 performance.mark() 和 performance.measure() 标记并计算时间间隔,结合 getEntriesByType('measure') 查看结果;还可监控渲染性能,获取 'first-paint' 和 'first-contentful-paint' 等关键指标;长时间运行应用需调用 performance.clearMarks() 和 performance.clearMeasures() 清理记录,避免内存堆积。合理使用可定位性能瓶颈,优化响应速度。

要精确分析JavaScript代码的执行性能,Performance API 是浏览器提供的强大工具集。它能提供高精度的时间戳,帮助开发者测量代码运行时长、识别性能瓶颈。相比 Date.now(),Performance API 的时间精度更高(可达纳秒级),且不受系统时钟偏移影响。
使用 performance.now() 获取高精度时间
performance.now() 返回从页面加载到当前调用时刻的毫秒数,精度远高于传统方法。适合测量小段代码的执行时间。
示例:
let start = performance.now();// 执行某段逻辑
for (let i = 0; i // 模拟耗时操作
}
let end = performance.now();
console.log(`耗时: ${end - start} 毫秒`);
利用 performance.mark() 和 performance.measure() 管理时间标记
对于复杂流程,可以使用标记(mark)和测量(measure)来组织性能数据。
立即学习“Java免费学习笔记(深入)”;
- performance.mark('label'):在某个时间点打上标记
- performance.measure('name', 'startMark', 'endMark'):计算两个标记之间的时间差
示例:
performance.mark('start');// 执行操作
someHeavyFunction();
performance.mark('after-heavy');
// 记录异步任务开始
setTimeout(() => {
performance.mark('end');
performance.measure('总耗时', 'start', 'end');
performance.measure('核心函数耗时', 'start', 'after-heavy');
// 查看结果
const measures = performance.getEntriesByType('measure');
measures.forEach(m => console.log(m.name, m.duration));
}, 0);
监控重排与重绘:结合 performance.getEntries() 分析渲染性能
Performance API 还支持记录资源加载、渲染帧等信息。通过 performance.getEntriesByType() 可获取特定类型的性能条目。
例如,分析脚本对渲染的影响:
// 在关键操作后记录渲染帧requestAnimationFrame(() => {
performance.mark('frame-end');
});
// 获取绘制相关数据
const paintEntries = performance.getEntriesByType('paint');
paintEntries.forEach(entry => {
console.log(entry.name, entry.startTime);
});
其中 'first-paint' 和 'first-contentful-paint' 对用户体验至关重要。
清理与优化:及时清除不必要的性能记录
长时间运行的应用中,频繁打点可能造成内存堆积。建议在分析完成后清除记录:
- performance.clearMarks():清除所有 mark
- performance.clearMeasures():清除所有 measure
- 可指定标签名清除特定项
例如:performance.clearMarks('start');
基本上就这些。合理使用 Performance API 能帮你精准定位慢函数、优化关键路径,提升整体响应速度。不复杂但容易忽略细节,比如记得在异步流程中正确标记时间点。











