Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Comparing the performance of generating 32-bit and 53-bit random numbers using the hat package vs the node.js built-in crypto module
crypto = require 'crypto'
hat = require 'hat'
hatRandom32 = -> +hat(32, 10)
cryptoRandom32 = ->
buffer = crypto.randomBytes(4)
buffer.readUInt32LE(0)
hatRandom53 = -> +hat(53, 10)
cryptoRandom53 = ->
buffer = crypto.randomBytes(8)
lower = buffer.readUInt32LE(0)
upper = buffer.readUInt32LE(4)
lower + (upper & 0x1FFFFF) * 4294967296
randomBufferSize = 512
randomBuffer = null
randomBufferOffset = randomBufferSize
bufferredCryptoRandom32 = ->
if randomBufferOffset is randomBufferSize
randomBufferOffset = 0
randomBuffer = crypto.randomBytes randomBufferSize
returnValue = randomBuffer.readUInt32LE randomBufferOffset
randomBufferOffset += 4
returnValue
bufferredCryptoRandom53 = ->
lower = bufferredCryptoRandom32()
upper = bufferredCryptoRandom32()
lower + (upper & 0x1FFFFF) * 4294967296
benchmark = (iterations, code)->
t0 = process.hrtime()
for i in [1..iterations]
code()
t1 = process.hrtime()
(t1[0] - t0[0]) * 1e9 + t1[1] - t1[0]
iterations = 10000000
console.log ['version ', process.versions.node]
console.log ['hat32 ', benchmark(iterations, hatRandom32) / iterations]
console.log ['crypto32 ', benchmark(iterations, cryptoRandom32) / iterations]
console.log ['bufferred32', benchmark(iterations, bufferredCryptoRandom32) / iterations]
console.log ['hat53 ', benchmark(iterations, hatRandom53) / iterations]
console.log ['crypto53 ', benchmark(iterations, cryptoRandom53) / iterations]
console.log ['bufferred53', benchmark(iterations, bufferredCryptoRandom53) / iterations]
[ 'version ', '4.2.4' ]
[ 'hat32 ', 694.3685562 ]
[ 'crypto32 ', 2040.4403699 ]
[ 'bufferred32', 131.2481266 ]
[ 'hat53 ', 982.3463352 ]
[ 'crypto53 ', 2034.880742 ]
[ 'bufferred53', 215.1741097 ]
[ 'version ', '4.3.2' ]
[ 'hat32 ', 662.5748487 ]
[ 'crypto32 ', 2164.7982519 ]
[ 'bufferred32', 155.8228151 ]
[ 'hat53 ', 1036.7472657 ]
[ 'crypto53 ', 2123.8128307 ]
[ 'bufferred53', 199.8784631 ]
[ 'version ', '4.4.1' ]
[ 'hat32 ', 715.8293629 ]
[ 'crypto32 ', 2030.0373721 ]
[ 'bufferred32', 126.3828921 ]
[ 'hat53 ', 975.0403035 ]
[ 'crypto53 ', 2104.9618644 ]
[ 'bufferred53', 190.0091236 ]
[ 'version ', '5.9.1' ]
[ 'hat32 ', 670.3050681 ]
[ 'crypto32 ', 1934.4135479 ]
[ 'bufferred32', 122.491949 ]
[ 'hat53 ', 969.8403003 ]
[ 'crypto53 ', 1947.8109037 ]
[ 'bufferred53', 223.7892894 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.