Skip to content

Commit

Permalink
crypto: improve randomBytes() performance
Browse files Browse the repository at this point in the history
PR-URL: #31519
Reviewed-By: James M Snell <[email protected]>
Reviewed-By: Tobias Nießen <[email protected]>
Reviewed-By: Rich Trott <[email protected]>
  • Loading branch information
mscdex authored and codebytere committed Mar 15, 2020
1 parent 4967bd0 commit 087ad9c
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
16 changes: 16 additions & 0 deletions benchmark/crypto/randomBytes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
'use strict';

const common = require('../common.js');
const { randomBytes } = require('crypto');

const bench = common.createBenchmark(main, {
size: [64, 1024, 8192, 512 * 1024],
n: [1e3],
});

function main({ n, size }) {
bench.start();
for (let i = 0; i < n; ++i)
randomBytes(size);
bench.end(n);
}
5 changes: 3 additions & 2 deletions lib/internal/crypto/random.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const {
} = primordials;

const { AsyncWrap, Providers } = internalBinding('async_wrap');
const { Buffer, kMaxLength } = require('buffer');
const { kMaxLength } = require('buffer');
const { randomBytes: _randomBytes } = internalBinding('crypto');
const {
ERR_INVALID_ARG_TYPE,
Expand All @@ -15,6 +15,7 @@ const {
} = require('internal/errors').codes;
const { validateNumber } = require('internal/validators');
const { isArrayBufferView } = require('internal/util/types');
const { FastBuffer } = require('internal/buffer');

const kMaxUint32 = 2 ** 32 - 1;
const kMaxPossibleLength = MathMin(kMaxLength, kMaxUint32);
Expand Down Expand Up @@ -52,7 +53,7 @@ function randomBytes(size, cb) {
if (cb !== undefined && typeof cb !== 'function')
throw new ERR_INVALID_CALLBACK(cb);

const buf = Buffer.alloc(size);
const buf = new FastBuffer(size);

if (!cb) return handleError(_randomBytes(buf, 0, size), buf);

Expand Down
1 change: 1 addition & 0 deletions test/benchmark/test-benchmark-crypto.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ runBenchmark('crypto',
'len=1',
'n=1',
'out=buffer',
'size=1',
'type=buf',
'v=crypto',
'writes=1',
Expand Down

0 comments on commit 087ad9c

Please sign in to comment.