0%

javascript-performance-monitor

介绍

今天我们来谈谈JavaScript中如何做性能监控,性能优化也是前端开发中的老话题了,做好性能优化的前提是要有性能监控,只有知道哪里有性能问题,才能有针对性的进行优化。
性能监控的方式多种多样,比如使用浏览器的开发者工具,使用第三方性能监控工具,或者自己编写代码来监控性能等。

今天我们主要介绍一下从代码层面如何做性能监控,JavaScript中提供了一个PerformanceObserver接口,可以用来监控性能相关的事件。

使用PerformanceObserver进行性能监控

首先我们需要定义一个PerformanceObserver实例。

1
2
3
4
5
const observer = new PerformanceObserver((list) => {
list.getEntries().forEach((entry) => {
console.log(`${entry.entryType}: ${entry.name} - ${entry.startTime} - ${entry.duration}`);
});
});

PerformanceObserver的构造函数,接受以下三个参数:

  1. entities - 这是一个PerformanceObserverEntryList对象,包含一系列可观察的性能事件。
  2. observer - 接收上述事件的观察者对象。
  3. options - 这是一个可选的配置对象,我们暂时用不到它,先忽略。

接下来,我们需要指定我们要监听的性能事件类型,比如longtaskmark等。

1
observer.observe({ entryTypes: ['longtask', 'mark'] });

可以使用PerformanceObserver中的静态函数PerformanceObserver.supportedEntryTypes来获取支持的性能事件类型。

1
console.log(PerformanceObserver.supportedEntryTypes);

在我的浏览器上,支持以下类型的性能事件:

1
2
3
4
5
6
7
8
9
10
11
12
13
"element"
"event"
"first-input"
"largest-contentful-paint"
"layout-shift"
"long-animation-frame"
"longtask"
"mark"`
"measure"
"navigation"
"paint"
"resource"
"visibility-state"

监控longtask事件

longtask任务是指阻塞主线程超过50毫秒的任务,我们首先来模拟一个longtask任务。

1
2
3
4
function simulateLongTask() {
const start = performance.now();
while (performance.now() - start < 50) {} // 模拟一个50毫秒的任务
}

接下来,我们在PerformanceObserver中监听longtask事件。

1
2
3
4
5
6
7
8
9
10
11
12
13
// Create a PerformanceObserver to observe long tasks
const observer = new PerformanceObserver((list) => {
const entries = list.getEntries();
entries.forEach((entry) => {
console.log("Long task detected:", entry);
});
});

// Start observing long tasks
observer.observe({ type: "longtask", buffered: true });

// Start the long task.
simulateLongTask();

打开控制台,可以看到如下输出,可以看到entryTypelongtask,表示这是一个长任务。duration表示任务的持续时间为50毫秒,满足长任务的条件。如果将simulateLongTask中的时间改为小于50毫秒,则不会触发longtask事件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Long task detected: PerformanceLongTaskTiming 
{
name: "self",
entryType: "longtask",
startTime: 10.299999997019768,
duration: 50,
attribution: [
{
name: "unknown",
entryType: "taskattribution",
startTime: 0,
duration: 0,
containerType: "window",
containerSrc: "",
containerId: "",
containerName: ""
}
]
}

参考

  1. https://developer.mozilla.org/en-US/docs/Web/API/PerformanceObserver