Console Log – Javascript Preformance in Chrome

Updated and Adjusted to accept optional arguments and track time or memory use as an indicator of performance.

If you are measuring Memory used please launch Chrome from Terminal.

By default, Chrome quantizes/rounds memory use making it inaccurate.

Run the following command from terminal to launch Chrome and prevent quantizing.

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --enable-precise-memory-info
// performanceType should be a string 'time' or 'memory'
// Optional Arguments (performanceType, divisor, precision, suffix)
var performanceCheck = function () {

  
  // Can't wait for defaults ES2015
  var divisor = 1;
  var precision = false;
  var suffix = (arguments[0] === 'memory') ? ' bytes' : ' ms';

  if (arguments.length > 1) {
    divisor = arguments[1];
  }
  
  if (arguments.length > 2) {
    precision = arguments[2];
  }

  if (arguments.length > 3) {
    suffix = arguments[3] || suffix;
  }

  var start;
  var func = (arguments[0] === 'memory') ? getMemoryUsed : getTime;
  var end;

  start = func();

  function getMemoryUsed() {
    return console.memory.usedJSHeapSize;
  }

  function getTime() {
    return Date.now();
  }

  function convertToUnits(num) {
    if (precision) return (num / divisor).toPrecision(precision);
    return (num / divisor);
  }

  function formatMsg(prefix, usage, suffix) {
    console.log(prefix + usage + suffix);
  }

  return function () {

    var total;
    
    end = func();
    
    total = end - start;

    formatMsg('Initial: ', convertToUnits(start), suffix); 
    formatMsg('Current: ', convertToUnits(end), suffix);
    formatMsg('Use: ', convertToUnits(total), suffix);

  }
}

// USAGE

// Set Initial Use Memory or Time
var check = performanceCheck('time');

// A javascript operation
var doJavascriptThings = [];
for (var i = 1000 - 1; i >= 0; i--) {
  doJavascriptThings[i] = [{'random':'values'}];
};

// Check again after process is complete
check();

Leave a Reply

Your email address will not be published. Required fields are marked *