批量测试多个函数的性能
要测试的函数数组
测试选项
const perf = new PerformanceMonitor()
const results = await perf.benchmark([
() => [1, 2, 3].map(x => x * 2),
() => [1, 2, 3].forEach((x, i, arr) => arr[i] = x * 2),
() => {
const result = []
for (const x of [1, 2, 3]) {
result.push(x * 2)
}
return result
}
], { iterations: 10000 })
results.forEach((result, index) => {
console.log(`函数${index + 1}: ${result.duration}ms`)
})
比较两个函数的性能
第一个函数
第二个函数
测试选项
const perf = new PerformanceMonitor()
const comparison = await perf.compare(
() => [1, 2, 3].map(x => x * 2),
() => {
const result = []
for (const x of [1, 2, 3]) {
result.push(x * 2)
}
return result
},
{ iterations: 10000 }
)
console.log(`函数1: ${comparison.fn1.duration}ms`)
console.log(`函数2: ${comparison.fn2.duration}ms`)
console.log(`性能差异: ${comparison.ratio.toFixed(2)}x`)
创建性能报告
性能测试结果数组
Optionallabels: string[]可选的标签数组
测试代码字符串的性能
要测试的代码字符串
测试选项
测试函数执行性能
要测试的函数
测试选项
const perf = new PerformanceMonitor()
// 基本测试
const result = await perf.measureFunction(() => {
return Array.from({ length: 1000 }, (_, i) => i * 2)
})
// 带选项的测试
const result2 = await perf.measureFunction(
() => someExpensiveOperation(),
{
iterations: 100,
warmupIterations: 10,
collectMemory: true,
forceGC: true
}
)
性能检测器类
提供测试JavaScript代码片段或方法执行性能的功能,支持多次迭代测试、 内存使用监控、预热执行等高级特性。
Example
Since
1.0.0