performance.markを簡単に使える関数を作成してパフォーマンス計測

performance.markとは

JavaScriptで処理時間を計測する際に使用するもので、performance.measureなどと併用することで処理時間を高精度で計測することができる。

new Date()を使用するよりも精度の高い計測ができて処理も軽いため、現在ではperformanceが使用されることが多い。

performanceは使い方がわかりにくい

便利なperformanceだがJavaScript初心者などが使うのは少し難しい。

しかし以下のperform関数を利用すればperformanceを簡単に使用できる。

※performanceはナノ秒まで計測可能だが通常はミリ秒まで計測できれば問題ないためMath.floorで小数点以下は切り下げてあります。

perform関数の使い方

まずコードの計測開始位置にperform('myStart');のような任意の名前を付けて記述する。

次に計測終了位置に開始位置に入れた名前と終了時の名前をperform('myStart', 'myEnd');のように記述すればconsole.logで計測時間がミリ秒で返ってくる。

function perform(start, end) {
  if (arguments.length === 1) {
    performance.mark(start);
  } else if (arguments.length === 2) {
    performance.mark(end);
    performance.measure('_' + start, start, end);
    console.log(
      start + ' 〜 ' + end + ': ' +
      Math.floor(performance.getEntriesByName('_' + start)[0].duration) + 'ms'
    );
  } else {
    throw new Error('arguments can set 1 or 2');
  }
}

// 計測開始
perform('myStart');

setTimeout(function() {
  // 計測終了
  perform('myStart', 'myEnd');
}, 1000);
// => myStart 〜 myEnd: 1000ms

開始名と終了名は日本語も可能だ。

perform('計測開始');

setTimeout(function() {
  perform('計測開始', '計測終了');
}, 1000);
// => 計測開始 〜 計測終了: 1000ms

performance.markを簡単に使える関数のサンプル