JavaScript内存获取

1,358 阅读1分钟

JavaScript内存获取

window.performance.memory是Google Chrome中的一项适当扩展程序,它提供了我们的JavaScript应用程序如何使用浏览器内存的一瞥。它公开了以下指标:

{
  totalJSHeapSize: 29400000,
  usedJSHeapSize: 15200000,
  jsHeapSizeLimit: 1530000000
}

使用示例

(function() {
  // Tune these for your application.
  var MAX_MEMORY_LIMIT = 20 * 1048576; // 20MB
  var MAX_PERCENT_THRESHOLD = 90;

  if (!window.performance || !window.performance.memory || !window.requestAnimationFrame || !window.trackJs) { return; }
  var hasAlarmed = false;

  requestAnimationFrame(function onFrame(){

    // Check if we've exceeded absolute memory limit
    if (performance.memory.usedJSHeapSize > MAX_MEMORY_LIMIT) {
      hasAlarmed = true;
      var overage = performance.memory.usedJSHeapSize - MAX_MEMORY_LIMIT;
      trackJs.track(new Error('Exceeded memory maximum limit by ' + overage + ' bytes'))
    }

    // Check if we've exceeded relative memory limit for client
    if (performance.memory.usedJSHeapSize > (MAX_PERCENT_THRESHOLD/100) * performance.memory.jsHeapSizeLimit) {
      hasAlarmed = true;
      trackJs.track(new Error('Memory usage exceeded ' + MAX_PERCENT_THRESHOLD + '% of maximum: ' + performance.memory.jsHeapSizeLimit))
    }

    // Only alert once
    if (!hasAlarmed) {
      requestAnimationFrame(onFrame);
    }
  });
})();