Last active
February 11, 2019 01:44
-
-
Save wemeetagain/32e94bdeedca36b3529590d99166046e to your computer and use it in GitHub Desktop.
BN vs number benchmark
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Benchmark = require('benchmark') | |
const BN = require('bn.js') | |
const suite = new Benchmark.Suite | |
let num_a, num_b | |
let bn_a, bn_b | |
const randInt = () => Math.floor(Math.random() * 2**24) | |
const genNewInputs = () => { | |
num_a = randInt() | |
num_b = randInt() | |
bn_a = new BN(num_a) | |
bn_b = new BN(num_b) | |
} | |
const options = { | |
onStart: genNewInputs, | |
onCycle: genNewInputs, | |
} | |
suite | |
.add('BN#add', () => bn_a.add(bn_b), options) | |
.add('BN#sub', () => bn_a.sub(bn_b), options) | |
.add('BN#div', () => bn_a.div(bn_b), options) | |
.add('BN#mul', () => bn_a.mul(bn_b), options) | |
.add('number#add', () => num_a + num_b, options) | |
.add('number#sub', () => num_a - num_b, options) | |
.add('number#div', () => Math.floor(num_a / num_b), options) | |
.add('number#mul', () => num_a * num_b, options) | |
.on('cycle', (evt) => console.log(String(evt.target))) | |
.run({async: true}) | |
/* | |
$ node --version | |
v10.15.1 | |
$ node bn_vs_number.js | |
BN#add x 42,634,555 ops/sec ±1.14% (91 runs sampled) | |
BN#sub x 21,596,668 ops/sec ±2.56% (84 runs sampled) | |
BN#div x 20,553,396 ops/sec ±8.56% (62 runs sampled) | |
BN#mul x 60,923,258 ops/sec ±1.62% (90 runs sampled) | |
number#add x 166,492,969 ops/sec ±0.21% (92 runs sampled) | |
number#sub x 166,453,714 ops/sec ±0.47% (93 runs sampled) | |
number#div x 167,928,989 ops/sec ±0.42% (89 runs sampled) | |
number#mul x 171,253,179 ops/sec ±0.39% (90 runs sampled) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment