Skip to content

Commit 9a3760d

Browse files
mscdexcodebytere
authored andcommitted
crypto: improve randomBytes() performance
PR-URL: #31519 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Tobias Nießen <tniessen@tnie.de> Reviewed-By: Rich Trott <rtrott@gmail.com>
1 parent baa14c9 commit 9a3760d

File tree

3 files changed

+20
-2
lines changed

3 files changed

+20
-2
lines changed

benchmark/crypto/randomBytes.js

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
'use strict';
2+
3+
const common = require('../common.js');
4+
const { randomBytes } = require('crypto');
5+
6+
const bench = common.createBenchmark(main, {
7+
size: [64, 1024, 8192, 512 * 1024],
8+
n: [1e3],
9+
});
10+
11+
function main({ n, size }) {
12+
bench.start();
13+
for (let i = 0; i < n; ++i)
14+
randomBytes(size);
15+
bench.end(n);
16+
}

lib/internal/crypto/random.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ const {
66
} = primordials;
77

88
const { AsyncWrap, Providers } = internalBinding('async_wrap');
9-
const { Buffer, kMaxLength } = require('buffer');
9+
const { kMaxLength } = require('buffer');
1010
const { randomBytes: _randomBytes } = internalBinding('crypto');
1111
const {
1212
ERR_INVALID_ARG_TYPE,
@@ -15,6 +15,7 @@ const {
1515
} = require('internal/errors').codes;
1616
const { validateNumber } = require('internal/validators');
1717
const { isArrayBufferView } = require('internal/util/types');
18+
const { FastBuffer } = require('internal/buffer');
1819

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

55-
const buf = Buffer.alloc(size);
56+
const buf = new FastBuffer(size);
5657

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

test/benchmark/test-benchmark-crypto.js

+1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ runBenchmark('crypto',
1919
'len=1',
2020
'n=1',
2121
'out=buffer',
22+
'size=1',
2223
'type=buf',
2324
'v=crypto',
2425
'writes=1',

0 commit comments

Comments
 (0)