Guest User

Untitled

a guest
Oct 23rd, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. const Benchmark = require('benchmark')
  2. const BigNumber = require('bignumber.js').BigNumber
  3. const Long = require('long')
  4.  
  5. const ITERATIONS_PER_CALL = 1000
  6.  
  7. const TEST_DATA_STRINGS = new Array(ITERATIONS_PER_CALL).fill(null).map((v, i) => String(i))
  8. const TEST_DATA_BUFFERS = TEST_DATA_STRINGS.map(str => Buffer.from(new BigNumber(str).toString(16).padStart(16, '0'), 'hex'))
  9.  
  10. const HIGH_WORD_MULTIPLIER = 0x100000000
  11.  
  12. const target = new Buffer(8)
  13.  
  14. const suite = new Benchmark.Suite()
  15. suite
  16. .add('Long serialize', function () {
  17. for (let i = 0; i < ITERATIONS_PER_CALL; i++) {
  18. const amount = Long.fromString(TEST_DATA_STRINGS[i], true)
  19. target.writeUInt32BE(amount.getHighBitsUnsigned())
  20. target.writeUInt32BE(amount.getLowBitsUnsigned(), 4)
  21. }
  22. })
  23. .add('Bignumber.js serialize', function () {
  24. for (let i = 0; i < ITERATIONS_PER_CALL; i++) {
  25. const uint64 = new BigNumber(TEST_DATA_STRINGS[i])
  26. target.writeUInt32BE(uint64.dividedToIntegerBy(HIGH_WORD_MULTIPLIER).toNumber())
  27. target.writeUInt32BE(uint64.modulo(HIGH_WORD_MULTIPLIER).toNumber(), 4)
  28. }
  29. })
  30. .add('Long deserialize', function () {
  31. for (let i = 0; i < ITERATIONS_PER_CALL; i++) {
  32. const highBits = TEST_DATA_BUFFERS[i].readUInt32BE()
  33. const lowBits = TEST_DATA_BUFFERS[i].readUInt32BE(4)
  34. Long.fromBits(+lowBits, +highBits, true).toString()
  35. }
  36. })
  37. .add('Bignumber.js deserialize', function () {
  38. for (let i = 0; i < ITERATIONS_PER_CALL; i++) {
  39. const highBits = TEST_DATA_BUFFERS[i].readUInt32BE()
  40. const lowBits = TEST_DATA_BUFFERS[i].readUInt32BE(4)
  41. const uint64 = new BigNumber(highBits).times(HIGH_WORD_MULTIPLIER).plus(lowBits)
  42. uint64.toString(10)
  43. }
  44. })
  45. .on('cycle', function(event) {
  46. console.log(String(event.target))
  47. })
  48. .on('complete', function() {
  49. console.log('Fastest is ' + this.filter('fastest').map('name'));
  50. })
  51. .on('error', function (err) {
  52. console.log('Error:', err)
  53. })
  54. .run({ async: true })
Add Comment
Please, Sign In to add comment