當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js vm.measureMemory([options])用法及代碼示例

vm.measureMemory([options])

添加於:v13.10.0
Stability: 1 - 實驗性

測量 V8 已知並由當前 V8 隔離或主上下文已知的所有上下文使用的內存。

  • options <Object>可選的。
    • mode <string> 'summary''detailed' 。在摘要模式下,僅返回為主上下文測量的內存。在詳細模式下,將返回為當前 V8 隔離已知的所有上下文測量的內存。 默認: 'summary'
    • execution <string> 'default''eager' 。在默認執行下,promise 將在下一次計劃的垃圾收集開始之後才會解析,這可能需要一段時間(或者如果程序在下一次 GC 之前退出,則永遠不會)。通過 Eager Execution,GC 將立即啟動以測量內存。 默認: 'default'
  • 返回: <Promise> 如果內存被成功測量,promise 將使用包含內存使用信息的對象來解決。

返回的 Promise 可以解析的對象的格式特定於 V8 引擎,並且可能會從 V8 的一個版本更改為下一個版本。

返回的結果與v8.getHeapSpaceStatistics()返回的統計數據不同之處在於vm.measureMemory()測量V8引擎當前實例中每個V8特定上下文可達的內存,而v8.getHeapSpaceStatistics()的結果測量每個堆占用的內存當前 V8 實例中的空間。

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);
  });

相關用法


注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 vm.measureMemory([options])。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。