浏览器 Performance API 极简总结博客
一、什么是 Performance API浏览器内置一套高精度计时标准挂载在全局window.performance对象上专门用来统计页面加载、JS 执行、网络请求、内存、主线程阻塞耗时精度到微秒不受系统时间修改影响是前端性能排查核心工具二、核心作用开发必用场景代码耗时监控统计循环、接口、组件渲染、复杂计算执行时长页面加载测速DNS、TCP、请求响应、首屏 FCP/LCP 全链路指标采集定位卡顿根源捕获主线程阻塞超 50ms 的长任务解决页面、点击交互卡顿排查内存泄漏Chrome 独有内存监控判断页面切换后内存是否只涨不跌线上性能埋点采集 Web VitalsLCP/CLS/INP上报后端统计真实用户体验Vue 组件渲染分析配合Vue.config.performance自动打点定位慢组件。三、核心属性大白话performance.timeOrigin页面打开的基准时间所有计时以此为起点performance.timing旧版废弃 老式页面加载时间对象数据杂乱不推荐新项目使用performance.memory仅 ChromeusedJSHeapSize当前实际占用内存 totalJSHeapSize浏览器分配总内存 jsHeapSizeLimit内存上限四、高频方法1、performance.now()返回页面运行至今的相对高精度时间戳对比Date.now优势不受系统时间篡改、带小数高精度。const s performance.now() // 业务逻辑 console.log(performance.now() - s)2、mark(标记名)自定义时间戳标记给一段代码打上起点 / 终点3、measure(名称, 起点标记, 终点标记)自动计算两个 mark 之间的执行耗时performance.mark(render-start) // 渲染逻辑 performance.mark(render-end) performance.measure(render-cost, render-start, render-end) const cost performance.getEntriesByName(render-cost)[0].duration配套清理clearMarks()/clearMeasures()清空标记防内存堆积。4、measure(名称, 起点标记, 终点标记)自动计算两个 mark 之间的执行耗时navigation页面加载全套指标新标准PerformanceNavigationTiming替代 timingresource所有 js/css/img/ 接口请求加载耗时定位大体积资源longtask主线程阻塞超过 50ms 的卡顿任务优化核心依据五、Vue 与原生 HTML 使用区别1、Vue 项目想要 Chrome 性能面板展示组件渲染耗时必须手动开启底层自动在组件生命周期执行 mark/measure 打点仅开发环境生效。// Vue2 Vue.config.performance true // Vue3 app.config.performance true2、原生 HTML/JS无需任何前置开启API 开箱即用需要监控代码时手动写 mark、measure。六、performance对象和PerformanceObserver类对比项window.performancePerformanceObserver本质全局内置对象监听构造函数类获取方式直接performance.xxxnew 实例后 observe 订阅数据模式主动一次性拉取被动自动回调监听使用场景临时查看、简单一次性采集线上埋点、持续监控 LCP/CLS/longtask是否自动更新不会必须重新调用方法有新性能数据自动触发回调performance 是全局对象主动一次性读取性能数据,无法自动捕获后续 新增性能数据需要定时轮询才能拿到页面运行中新产生的 longtask、 LCP等性能指标。 PerformanceObserver监听类异步订阅,需要实例化, 性能监听器 订阅后自动捕获新增指标, 是持续性监听performance 就像快照一样 拿到某一时刻的信息。七、计算执行时长片段start(name, detail {}) { if (!window.performance) return; performance.mark(${name}_start, { detail }); }, end(name) { if (!window.performance) return null; const startMark ${name}_start; const endMark ${name}_end; const measureName ${name}_cost; performance.mark(endMark); performance.measure(measureName, startMark, endMark); const entry performance.getEntriesByName(measureName)[0]; const duration entry?.duration || 0; // 新增读取并打印 detail const startMarkEntries performance.getEntriesByName(startMark); if (startMarkEntries.length) { const startMarkItem startMarkEntries[0]; console.log(【${name}】附加业务数据,startMarkItem.detail); } performance.clearMarks(startMark); performance.clearMarks(endMark); performance.clearMeasures(measureName); return duration; } // 使用案例 this.start(task-list-load, { name: task-list-load, detail: task-list-load }); setTimeout(() { const time this.end(task-list-load); console.log(任务列表加载耗时, this.formatMs(time)); }, 2000);