在前端开发过程中,函数执行的性能直接影响页面的响应速度和用户体验,因此掌握JS函数性能监测的定义方式和执行时间计算方法,是开发者优化代码的基础能力。通过合理的性能监测,我们可以快速定位执行耗时的函数,针对性进行优化。

一、使用performance API定义性能监测
performance是浏览器提供的原生性能监测API,精度高于普通的时间戳计算,适合需要高精度执行时间的场景。我们可以通过performance.now()方法获取当前时间的高精度时间戳,计算函数执行前后的时间差得到执行耗时。
以下是一个简单的性能监测函数定义示例:
// 定义性能监测函数,接收要监测的目标函数和参数
function monitorFunctionPerformance(func, ...args) {
// 获取函数执行前的时间戳
const startTime = performance.now();
// 执行目标函数,传入参数
const result = func.apply(null, args);
// 获取函数执行后的时间戳
const endTime = performance.now();
// 计算执行耗时,保留两位小数
const costTime = (endTime - startTime).toFixed(2);
console.log(`函数执行耗时:${costTime}毫秒`);
// 返回函数执行结果
return result;
}
// 定义一个测试用的耗时函数
function testSlowFunction(count) {
let sum = 0;
for (let i = 0; i < count; i++) {
sum += i;
}
return sum;
}
// 调用监测函数
monitorFunctionPerformance(testSlowFunction, 10000000);
二、使用console.time方法定义性能监测
console.time是控制台提供的简易计时方法,使用起来更加简洁,适合快速调试场景。该方法通过传入一个标识字符串作为计时器的名称,调用console.timeEnd结束计时并输出耗时。
我们可以封装一个基于console.time的性能监测函数:
// 定义基于console.time的性能监测函数
function monitorWithConsoleTime(func, timerName, ...args) {
// 启动计时器,timerName为计时器标识
console.time(timerName);
// 执行目标函数
const result = func.apply(null, args);
// 结束计时器并输出耗时
console.timeEnd(timerName);
return result;
}
// 测试调用
monitorWithConsoleTime(testSlowFunction, 'testSlowFunction', 10000000);
需要注意的是,同一个计时器标识不能同时启动多个,否则会导致计时结果异常。
三、手动时间戳计算执行时间
如果需要兼容不支持performance API的环境,可以使用Date对象的时间戳进行计算,不过精度相对较低,适合对时间精度要求不高的场景。
// 基于Date时间戳的性能监测函数
function monitorWithDate(func, ...args) {
// 获取执行前的时间戳,单位是毫秒
const startTime = new Date().getTime();
const result = func.apply(null, args);
const endTime = new Date().getTime();
const costTime = endTime - startTime;
console.log(`函数执行耗时:${costTime}毫秒`);
return result;
}
// 测试调用
monitorWithDate(testSlowFunction, 10000000);
四、不同方法的对比与选择
我们可以通过下表对比三种方法的特性,根据实际场景选择:
| 方法 | 精度 | 使用复杂度 | 适用场景 |
|---|---|---|---|
| performance API | 高(微秒级) | 中等 | 需要高精度计时的性能分析场景 |
| console.time | 中等 | 低 | 快速调试、临时性能验证场景 |
| Date时间戳 | 低(毫秒级) | 低 | 兼容低版本环境、对精度要求不高的场景 |
五、封装可复用的性能监测装饰器
如果需要对多个函数添加性能监测,可以封装一个装饰器函数,避免重复编写监测逻辑:
// 性能监测装饰器,接收一个函数,返回带性能监测功能的新函数
function performanceDecorator(func) {
return function(...args) {
const startTime = performance.now();
const result = func.apply(this, args);
const endTime = performance.now();
const costTime = (endTime - startTime).toFixed(2);
console.log(`函数${func.name}执行耗时:${costTime}毫秒`);
return result;
};
}
// 使用装饰器包装目标函数
const monitoredSlowFunction = performanceDecorator(testSlowFunction);
// 调用包装后的函数
monitoredSlowFunction(10000000);
这种方式可以在不修改原函数代码的前提下,为函数添加性能监测能力,符合开闭原则,适合在项目中批量使用。
JavaScript函数性能监测执行时间计算performance_APIconsole_time修改时间:2026-07-22 19:24:26