Skip to content

Instantly share code, notes, and snippets.

@alexvictoor
Created October 28, 2018 15:07
Show Gist options
  • Save alexvictoor/fa518189c3534fce10ce5cfad3d07c8f to your computer and use it in GitHub Desktop.
Save alexvictoor/fa518189c3534fce10ce5cfad3d07c8f to your computer and use it in GitHub Desktop.
BigInt bitwise micro benchmark

BigInt divide benchmark

BigInt, integers using 64 bits are now available with latest v8, hence NodeJS and Chrome browsers.
With good old JavaScript numbers, bitwise operators are only working on 32 bits.
Now with BigInts, bitwise operators work on 64 bits! The aim of this microbenchmark is to assess the performances of the '>>' operators to divide an integer.

To run the bench:

    yarn install
    node bitwise-bench.js

Results using node v10.11.0 on a MBP 2017:

Number divide x 728,685,410 ops/sec ±1.34% (83 runs sampled)
BigInt divide x 22,162,527 ops/sec ±0.76% (92 runs sampled)
BigInt bitwise x 26,741,007 ops/sec ±0.40% (91 runs sampled)
Fastest is Number divide

Sadly bitwise operators are as slow with BigInt as with Number :(

Let me know if you thinnkk I made an obvious mistake. I am sure there is room for improvement. Feedbacks are welcome!

const Benchmark = require('benchmark');
const suite = new Benchmark.Suite;
// add tests
suite.add('Number divide', function() {
Math.round(input / 256);
},
{
'setup': function() {
var input = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER );
}
})
.add('BigInt divide', function() {
input / 256n;
},
{
'setup': function() {
var input = BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER ));
}
})
.add('BigInt bitwise', function() {
input >> 8n;
},
{
'setup': function() {
var input = BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER ));
}
})
// add listeners
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').map('name'));
})
// run async
.run({ 'async': true });
{
"name": "bit-bench",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"benchmark": "^2.1.4"
}
}
@mattbishop
Copy link

I added another test to check number bitwise too:

  .add('Number bitwise', function() {
      input >> 8;
    },
    {
      'setup': function() {
        var input = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER );
      }
    })

Number divide x 619,531,374 ops/sec ±1.02% (86 runs sampled)
BigInt divide x 10,780,787 ops/sec ±1.88% (81 runs sampled)
Number bitwise x 610,695,732 ops/sec ±1.12% (83 runs sampled)
BigInt bitwise x 13,353,902 ops/sec ±1.12% (84 runs sampled)
Fastest is Number divide,number bitwise

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment