node.js べき乗計算ができる「Math.pow」と「べき乗演算子」のパフォーマンスを計測する

node.js べき乗計算ができる「Math.pow」と「べき乗演算子」のパフォーマンスを計測する

node.jsで、べき乗計算を行う際に利用する「Math.pow」と「べき乗演算子」のパフォーマンスを計測するサンプルコードを記述してます。nodeのバージョンは14.15.1を使用してます。

環境

  • OS windows10 pro 64bit
  • node V14.15.1

パフォーマンス計測

benchmarkを使用して、「Math.pow」と「べき乗演算子」を使用して、べき乗計算を行うコードを実行して、パフォーマンスを計測した結果を表示します。

benchmarkインストール

npm i benchmark

パフォーマンス計測コード

const Benchmark = require('benchmark');

const suite = new Benchmark.Suite;

suite
    .add('pow', function() {
        Math.pow(2, 8);
    })
    .add('**', function() {
        2 ** 8;
    })
    .on('cycle', function(event) {
        console.log(String(event.target));
    })
    .on('complete', function() {
        console.log('パフォーマンスがいいのは ' + this.filter('fastest').map('name') + 'となります');
    })
    // run async
    .run({ 'async': true });

実行結果 (benchmarkを少しだけ日本語化してます)

[1回目]
pow x 698,871,005 回/秒 ±1.97% (83 runs sampled)
** x 686,058,197 回/秒 ±1.72% (82 runs sampled)
パフォーマンスがいいのは pow,**となります

[2回目]
pow x 699,617,837 回/秒 ±2.00% (84 runs sampled)
** x 679,347,237 回/秒 ±1.56% (81 runs sampled)
パフォーマンスがいいのは pow,**となります

[3回目]
pow x 696,710,901 回/秒 ±1.97% (81 runs sampled)
** x 679,031,146 回/秒 ±1.49% (81 runs sampled)
パフォーマンスがいいのは pow,**となります
パフォーマンスがいいのは floor,|となります

1秒間に実行できる回数をみると、特にどちらを使用してもパフォーマンスに変化はなさそうな結果となりました。