indutny / bn.js

BigNum in pure javascript
MIT License
1.2k stars 151 forks source link

optimize toBitArray function #212

Closed fanatid closed 5 years ago

fanatid commented 5 years ago

Remove extra bitwise operator

performance:

  function toBitArray1 (num) {
    var w = new Array(num.bitLength());

    for (var bit = 0; bit < w.length; bit++) {
      var off = (bit / 26) | 0;
      var wbit = bit % 26;

      w[bit] = (num.words[off] >>> wbit) & 0x01;
      // w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
    }

    return w;
  }

  function toBitArray2 (num) {
    var w = new Array(num.bitLength());

    for (var bit = 0; bit < w.length; bit++) {
      var off = (bit / 26) | 0;
      var wbit = bit % 26;

      // w[bit] = (num.words[off] >>> wbit) & 0x01;
      w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
    }

    return w;
  }

const z = new BN(require('crypto').randomBytes(32))
console.time('toBitArray1')
for (let i = 0; i < 1e5; ++i) toBitArray1(z)
console.timeEnd('toBitArray1')
console.time('toBitArray2')
for (let i = 0; i < 1e5; ++i) toBitArray2(z)
console.timeEnd('toBitArray2')

// toBitArray1: 85.165ms
// toBitArray2: 96.260ms