Performance API 与性能调优|青训营

86 阅读2分钟

为了测试性能,常规地就是使用内置 Date 对象标记某个操作开始结束的时间。

const start = new Date().getTime();
doSomething();
const end = new Date().getTime();
console.log('elapsed: ', end - start);

更进一步,还可以配合使用 console.timeconsole.timeEnd 记录操作耗时,上面的例子等效为如下代码。

console.time("doSomething()");
doSomething();
console.timeEnd("doSomething()");

console.timeconsole.timeEnd 都需要传入一个“标签”,当调用 console.timeEnd 时会自动计算并打印自上次相同标签的 console.time 调用所经过的时间。

但这两种方法都有两个不足:它无法分析一些后台事件的性能消耗,比如网页加载时间、某个资源的请求耗时又或是脚本的解析时间……毕竟我们没有插入也不太可能插入 console.timeconsole.timeNnd。其次就是 Date.getTime 返回的时间戳被限制在一毫秒的精确度内,对精度要求较高的场景不太适用。

Performance API 正好具备此种能力,它是由 ECMAScript 5 引入的,主流的浏览器均已支持。不仅如此,Node.js 也支持 Performance API

其中 performance.now() 返回自 performance.timing.navigationStart 到当前时间的差值,它以浮点数的形式表示,精度最高可达微秒级。但是,“为了提供对定时攻击和指纹的保护”,其精度可能会根据浏览器的设置而被舍弃,因此 performance.timing.navigationStart + performance.now() 约等于 Date.now()。(参考:MDN Performance.now())。

我们完全可以使用 performance.now() 替代 console.time 获取更高精度的结果。

const start = performance.now();
doSomething();
const end = performance.now();
console.log('elapsed: ', end - start);

performance.getEntries 方法将返回一个由 PerformanceEntry 对象组成的数组,每个 PerformanceEntry 对象都记录了浏览器中的某项操作的性能指标。当然,我们也可以使用 performance.markperformance.measure 手动记录某项操作,并创建 PerformanceEntry

image.png (图源:MDN)

下图是 MDN 的性能表现,其中记录了操作的细节,以及开始时间,用时多少等等信息。我们完全可以利用这些信息做可视化分析网站性能瓶颈。

image.png

事实上,浏览器调试工具已经集成了相应功能:网络、帧、动画和函数调用图都有详细的可视化图表。比起 console.time 简直太强大了。

image.png

性能调优迟早是要做的,一些指标(比如“首屏渲染时间”)会极大影响用户体验。Performance API 以及 Performance 面板是非常优秀和成熟的性能调优工具,不仅能通过图表分析出性能瓶颈,大多数时候还能定位到代码。Chrome 浏览器提供了一个调优实例,感兴趣可以查看:googlechrome.github.io/devtools-sa…