Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
crypto: improve randomBytes() performance
  • Loading branch information
mscdex committed Jan 26, 2020
commit 1b1830a4bd445839432ed0230f44924164df0482
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