From 3c6545f0b40238a2ba17ab599878219317cc0b05 Mon Sep 17 00:00:00 2001 From: Brian White Date: Sun, 26 Jan 2020 07:28:57 -0500 Subject: [PATCH] crypto: improve randomBytes() performance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/31519 Reviewed-By: James M Snell Reviewed-By: Tobias Nießen Reviewed-By: Rich Trott --- benchmark/crypto/randomBytes.js | 16 ++++++++++++++++ lib/internal/crypto/random.js | 5 +++-- test/benchmark/test-benchmark-crypto.js | 1 + 3 files changed, 20 insertions(+), 2 deletions(-) create mode 100644 benchmark/crypto/randomBytes.js diff --git a/benchmark/crypto/randomBytes.js b/benchmark/crypto/randomBytes.js new file mode 100644 index 00000000000000..50ad3f08387566 --- /dev/null +++ b/benchmark/crypto/randomBytes.js @@ -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); +} diff --git a/lib/internal/crypto/random.js b/lib/internal/crypto/random.js index 85855a709e89fd..801c0eb8789fcd 100644 --- a/lib/internal/crypto/random.js +++ b/lib/internal/crypto/random.js @@ -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, @@ -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); @@ -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); diff --git a/test/benchmark/test-benchmark-crypto.js b/test/benchmark/test-benchmark-crypto.js index f24edf675f92f0..6ba71471cf4be2 100644 --- a/test/benchmark/test-benchmark-crypto.js +++ b/test/benchmark/test-benchmark-crypto.js @@ -19,6 +19,7 @@ runBenchmark('crypto', 'len=1', 'n=1', 'out=buffer', + 'size=1', 'type=buf', 'v=crypto', 'writes=1',