Date接口
业务场景
试想一般场景下,在浏览器中是如何计算两个时刻之间的持续时间?大多数人或许会立即联想到Date.now()接口
// Date对象记录(DOMTimeStamp)自1970年1月1日00:00:00(UTC)到当前的毫秒数
const start = Date.now()
// do something
const end = Date.now()
const during = start - end
但是在 ECMA-262 第5版(2009,11)的实现上Date接口存在许多问题,在W3C定义的Performance High Time(2012 )文档中明确指出(在定义初期)Date.now()的时间在亚毫秒级的记录并不准确
For example, the following script may log a positive number, negative number, or zero.
var mark_start = Date.now();
doTask(); // Some task
if (window.console) window.console.log('Duration of task: ' + (Date.now() - mark_start));
Date的缺陷
由于Date接口提供的时间戳存在以下缺陷
- 提供的不是稳定的单调时钟,会因目标系统的不同出现偏差
- 不能提供亚毫秒的时间记录接口 在一般业务中,毫秒级误差的影响几乎可以忽略,但是对于计量浏览器性能而言,失之毫厘谬以千里,所以需要一个精确度更高的接口记录时间,所以W3C定义了Web Performance Working Group为浏览器性能级计算提供高性能接口支持
高精度测量方法集
简介
Web Performance Working Group 就是W3C为用户测量应用的性能提供高精度测量方法集
内容
- High resolution time : 定义了DOMHightResTimeStamp 和 原始Performance
- Performance timeline : 定义了存储性能信息的数据结构(PerformanceEntry)、监测接口PerformanceObserver 和(扩展了)获取接口(Performance)
- Resource-timing:定义了所有资源完整计时信息的接口
- Navigation timing:定义了用于访问文档完整时间信息的Web应用程序接口
- User tming:提供了用户自定义测量的高性能时间戳接口:PerformanceMark(mark)和 PerformanceMeasure(measure)
- ...等等多个内容
发展现状
随着需求的增加、对性能的认识的更深,规范的内容也在不断迭代中,而各模块的内容更新速度并不一致,所以会出现部分内容处在不同的阶段(level)。
在实现上,甚至新旧接口同时存在,如PerformanceTiming在MDN已标记为废弃
发展时间轴
根据接口的更新情况可Performance划分为3个发展阶段
- ECMA-262 第5版定义Date接口
- Perforcemance 各模块定义 level 1阶段前后
- Perforcemance 各模块定义 level 2阶段前后,level 1 官方标志废弃,但仍保留其接口
主要类及属性
在浏览器中通过window.performance调用相关的性能检测方法, 可直接通过控制台观察其内部属性(如上文所述,实现上新旧接口同时存在)
以测试浏览器为Chrome 91.0.4472.124,performance部分属性包括:
1.eventCounts:记录(36个)默认事件浏览器触发次数
const pr = window.performance const eventNames = [...pr.eventCounts.keys()]
const time = pr.eventCounts.get("mousedown")
- memory(Device Memory)
// https://developer.mozilla.org/zh-CN/docs/Web/API/Performance/memory
// pr.memory
{
jsHeapSizeLimit // 上下文内可用堆的最大体积
totalJSHeapSize // 已分配的堆体积
usedJSHeapSize // 当前 JS 堆活跃段(segment)的体积
}
- navigation , timing 【注意】该接口为level 1 标准的实现,在level 2中已变更为type为navigation 的PerformanceEntry对象记录,详情请看navitagtion-timing level 2
参考链接
Web Performance Working Group git
Web Performance Working Group