node.js 少数の切り捨てを行う「Math.floor」と「~~」と「|」のパフォーマンスを計測する

node.js 少数の切り捨てを行う「Math.floor」と「~~」と「|」のパフォーマンスを計測する

node.jsで、少数の切り捨てを行う際に利用する「Math.floor」と「~~」と「|」のパフォーマンスを計測するサンプルコードを記述してます。nodeのバージョンは14.15.1を使用してます。

環境

  • OS windows10 pro 64bit
  • node V14.15.1

パフォーマンス計測

benchmarkを使用して、「Math.floor」と「~~」と「|」を使用して、少数の切り捨てを行うコードを実行して、パフォーマンスを計測した結果を表示します。

benchmarkインストール

npm i benchmark

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

const Benchmark = require('benchmark');

const suite = new Benchmark.Suite;

suite
    .add('floor', function() {
        Math.floor(1.2345);
    })
    .add('~~', function() {
        ~~1.2345;
    })
    .add('|', function() {
        1.2345 | 0;
    })
    .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回目]
floor x 709,500,969 回/秒 ±2.08% (85 runs sampled)
~~ x 693,349,926 回/秒 ±1.88% (80 runs sampled)
| x 688,328,880 回/秒 ±1.75% (80 runs sampled)
パフォーマンスがいいのは floor,|となります

[2回目]
floor x 690,998,892 回/秒 ±1.84% (82 runs sampled)
~~ x 692,491,873 回/秒 ±1.82% (82 runs sampled)
| x 690,916,438 回/秒 ±1.81% (82 runs sampled)
パフォーマンスがいいのは ~~,|となります

[3回目]
floor x 697,061,392 回/秒 ±1.93% (81 runs sampled)
~~ x 691,799,266 回/秒 ±1.82% (81 runs sampled)
| x 682,531,573 回/秒 ±1.60% (82 runs sampled)
パフォーマンスがいいのは floor,|となります

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