Skip to content

Commit

Permalink
[perf] Reduce the amount of crypto.randomFillSync() calls
Browse files Browse the repository at this point in the history
Use a pool of random bytes to reduce the amount of
`crypto.randomFillSync()` calls.

Refs: nodejs/undici#3204
  • Loading branch information
lpinca committed May 18, 2024
1 parent b73b118 commit ddfe4a8
Showing 1 changed file with 16 additions and 1 deletion.
17 changes: 16 additions & 1 deletion lib/sender.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ const { mask: applyMask, toBuffer } = require('./buffer-util');

const kByteLength = Symbol('kByteLength');
const maskBuffer = Buffer.alloc(4);
const RANDOM_POOL_SIZE = 8 * 1024;
let randomPool;
let randomPoolPointer = RANDOM_POOL_SIZE;

/**
* HyBi Sender implementation.
Expand Down Expand Up @@ -76,7 +79,19 @@ class Sender {
if (options.generateMask) {
options.generateMask(mask);
} else {
randomFillSync(mask, 0, 4);
if (randomPoolPointer === RANDOM_POOL_SIZE) {
if (randomPool === undefined) {
randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
}

randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
randomPoolPointer = 0;
}

mask[0] = randomPool[randomPoolPointer++];
mask[1] = randomPool[randomPoolPointer++];
mask[2] = randomPool[randomPoolPointer++];
mask[3] = randomPool[randomPoolPointer++];
}

skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
Expand Down

0 comments on commit ddfe4a8

Please sign in to comment.