Performance API 是浏览器提供的高精度性能监控接口,通过 window.performance 实现;它支持微秒级时间测量,常用方法包括 performance.now()、mark()、measure() 和 getEntriesByType(),可用于精准分析 JavaScript 执行耗时与页面渲染性能。

在现代Web开发中,JavaScript性能直接影响用户体验。为了精准分析和优化运行效率,浏览器提供了强大的 Performance API。它不仅可用于测量页面加载时间,还能监控JavaScript代码的执行耗时、内存使用情况以及关键渲染路径等核心指标。
Performance API 是一套内置于现代浏览器的标准接口,用于获取高精度的时间戳和性能相关数据。它属于 W3C Performance Timeline 规范的一部分,主要通过 window.performance 对象暴露给开发者。
该API的核心优势在于提供微秒级精度的时间测量(比 Date.now() 更精确),适合用于细粒度性能分析。
以下是 Performance API 中最实用的功能点:
立即学习“Java免费学习笔记(深入)”;
下面是一个监控某段 JavaScript 函数执行时间的典型用法:
// 标记开始
performance.mark('start-processing');
<p>// 模拟一段耗时操作
const data = Array.from({ length: 1e6 }, (_, i) => i * i).filter(x => x % 2);</p><p>// 标记结束
performance.mark('end-processing');</p><p>// 创建测量
performance.measure('data-processing-time', 'start-processing', 'end-processing');</p><p>// 获取结果
const measures = performance.getEntriesByType('measure');
measures.forEach(m => {
console.log(<code>${m.name}: ${m.duration.toFixed(2)} ms</code>);
});</p>输出类似:data-processing-time: 15.43 ms,帮助你识别性能瓶颈。
User Timing API 是 Performance API 的扩展,允许开发者自定义标记和测量,非常适合监控关键交互,比如按钮点击到响应完成的时间。
你可以这样监控首屏内容渲染时间:
// 在关键元素渲染完成后打标
if (document.getElementById('hero-banner')) {
performance.mark('hero-rendered');
}
<p>// 计算从导航开始到渲染完成的时间
performance.measure(
'time-to-hero',
'navigationStart',
'hero-rendered'
);</p>之后可通过上报机制将这些数据发送到分析系统,用于长期性能追踪。
基本上就这些。合理使用 Performance API 能帮你定位 JavaScript 执行慢、卡顿等问题,是性能优化不可或缺的工具。
以上就是JavaScript中的性能监控API:Performance_javascript性能优化的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号