node:v8
获得代码相关的统计信息
在代码的不同位置打印,可以获得当前的代码相关的统计信息
import v8 from 'node:v8'
const heapCodeStats = v8.getHeapCodeStatistics()
console.log(heapCodeStats)
/**
{
code_and_metadata_size: 565360, // 已编译代码和元数据的总大小
bytecode_and_metadata_size: 449960, // 字节码和元数据的总大小
external_script_source_size: 1254211
}
*/分析内存占用
内存堆的快照会随着程序的运行发生变化,下面的代码可以在合适的地方插入,查看当前的内存状态
import v8 from 'node:v8'
import fs from 'node:fs'
const heapSnapshotStream = v8.getHeapSnapshot();
const snapshotFile = fs.createWriteStream("HeapSnapshot.heapsnapshot");
heapSnapshotStream.pipe(snapshotFile);生成的 heapsnapshot 文件,可以在 VSCode 中查看,或者在 Chrome DevTool 的 Memory 下面上传文件预览
帮助我们:
- 发现内存泄漏:某些内存意外地没有被回收
- 优化内存使用:优化某些占用了大量内存的对象
获取堆快照
import v8 from 'node:v8'
const heapStats = v8.getHeapStatistics();
console.log(heapStats);
/**
{
total_heap_size: 12140544,
total_heap_size_executable: 1048576,
total_physical_size: 10016632,
total_available_size: 4337376568,
used_heap_size: 7482864,
heap_size_limit: 4345298944,
malloced_memory: 536848,
peak_malloced_memory: 6258568,
does_zap_garbage: 0,
number_of_native_contexts: 2,
number_of_detached_contexts: 0,
total_global_handles_size: 16384,
used_global_handles_size: 8512,
external_memory: 2380815
}
*/