vm.measureMemory([options])


稳定性: 1 - 实验性

测量 V8 所知的内存,以及当前 V8 isolate 或主上下文中所有已知上下文使用的内存。

🌐 Measure the memory known to V8 and used by all contexts known to the current V8 isolate, or the main context.

  • options <Object> 可选。
    • mode <string> 要么是 'summary',要么是 'detailed'。在摘要模式下,只会返回为主上下文测量的内存。在详细模式下,会返回为当前 V8 isolate 已知的所有上下文测量的内存。默认值: 'summary'
    • execution <string> 要么是 'default',要么是 'eager'。使用默认执行时,Promise 在下一次计划的垃圾回收开始之前不会解析,这可能需要一段时间(如果程序在下一次 GC 之前退出,则可能永远不会解析)。使用主动执行时,垃圾回收会立即启动以测量内存。 默认值: 'default'
  • 返回:<Promise> 如果内存测量成功,Promise 将会解析为一个包含内存使用信息的对象。否则,它将以 ERR_CONTEXT_NOT_INITIALIZED 错误被拒绝。

返回的 Promise 可能解析的对象格式是 V8 引擎特有的,并且可能会随着 V8 的不同版本而变化。

🌐 The format of the object that the returned Promise may resolve with is specific to the V8 engine and may change from one version of V8 to the next.

返回的结果与 v8.getHeapSpaceStatistics() 返回的统计数据不同,因为 vm.measureMemory() 测量的是当前 V8 引擎实例中每个特定 V8 上下文可访问的内存,而 v8.getHeapSpaceStatistics() 的结果测量的是当前 V8 实例中每个堆空间所占用的内存。

🌐 The returned result is different from the statistics returned by v8.getHeapSpaceStatistics() in that vm.measureMemory() measure the memory reachable by each V8 specific contexts in the current instance of the V8 engine, while the result of v8.getHeapSpaceStatistics() measure the memory occupied by each heap space in the current V8 instance.

const vm = require('node:vm');
// Measure the memory used by the main context.
vm.measureMemory({ mode: 'summary' })
  // This is the same as vm.measureMemory()
  .then((result) => {
    // The current format is:
    // {
    //   total: {
    //      jsMemoryEstimate: 2418479, jsMemoryRange: [ 2418479, 2745799 ]
    //    }
    // }
    console.log(result);
  });

const context = vm.createContext({ a: 1 });
vm.measureMemory({ mode: 'detailed', execution: 'eager' })
  .then((result) => {
    // Reference the context here so that it won't be GC'ed
    // until the measurement is complete.
    console.log(context.a);
    // {
    //   total: {
    //     jsMemoryEstimate: 2574732,
    //     jsMemoryRange: [ 2574732, 2904372 ]
    //   },
    //   current: {
    //     jsMemoryEstimate: 2438996,
    //     jsMemoryRange: [ 2438996, 2768636 ]
    //   },
    //   other: [
    //     {
    //       jsMemoryEstimate: 135736,
    //       jsMemoryRange: [ 135736, 465376 ]
    //     }
    //   ]
    // }
    console.log(result);
  });