在Debian上进行JS性能测试,可结合工具与代码实现,以下是具体方法:
# 安装Node.js和npm
curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
sudo apt-get install -y nodejs npm
# 安装常用测试工具
sudo apt-get install apache2-utils wrk # ApacheBench、wrk
npm install -g benchmark.js artillery # Benchmark.js、Artillery
通过perf_hooks
模块获取代码执行时间:
// test.js
const { performance } = require('perf_hooks');
const start = performance.now();
// 待测试代码(如循环、函数调用)
for (let i = 0; i < 1e7; i++) {}
const end = performance.now();
console.log(`执行时间: ${end - start} 毫秒`);
运行:node test.js
Benchmark.js:用于评估代码片段性能
// benchmark.js
const Benchmark = require('benchmark');
new Benchmark.Suite()
.add('字符串替换', () => 'hello'.replace(/./g, 'x'))
.on('complete', function() {
console.log(this.map('toString').join('\n'));
})
.run({ async: true });
运行:node benchmark.js
wrk:模拟高并发HTTP请求
wrk -t12 -c400 -d30s http://localhost:3000 # 12线程,400并发,持续30秒
Artillery:测试REST接口性能
# scenarios.yml
scenarios:
- flow:
- get:
url: "/api/data"
artillery run scenarios.yml
内存泄漏检测:使用heapdump
生成快照,通过Chrome DevTools分析
npm install heapdump
# 在代码中引入:const heapdump = require('heapdump');
# 触发内存快照:heapdump.writeSnapshot('./heapdump.heapsnapshot');
分析:Chrome DevTools → Memory面板 → 加载快照对比
综合性能监控:通过Lighthouse生成性能报告
# 安装Lighthouse
npm install -g lighthouse
lighthouse http://localhost:3000 --view
根据测试目标选择工具,优先通过perf_hooks
和Benchmark.js定位代码级性能问题,再通过wrk、Artillery模拟负载场景,最终结合浏览器工具和线上监控验证优化效果。