crypto: optimize normalizeAlgorithm dispatch hot path

Replace the O(n) case-insensitive algorithm-name scan
with an O(1) SafeMap lookup. The map is pre-built at
module init alongside kSupportedAlgorithms.

Hoist the opts object literal used in normalizeAlgorithm
to module level to avoid allocating identical
{ prefix, context } objects on every call.

Pre-compute ObjectKeys() for simpleAlgorithmDictionaries
entries at module init to avoid allocating a new keys
array on every normalizeAlgorithm call.

Signed-off-by: Filip Skokan <panva.ip@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/62756
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
This commit is contained in:
Filip Skokan authored and Antoine du Hamel committed 2026-07-30 13:51:20 +02:00
1 parent 9623d9ad85
commit 8bb536066d
1 file changed
+57 -49
+57 -49
View File
@@ -17,6 +17,7 @@ const {
PromisePrototypeThen,
PromiseReject,
PromiseWithResolvers,
SafeMap,
SafeSet,
StringPrototypeToUpperCase,
Symbol,
@@ -455,8 +456,11 @@ const experimentalAlgorithms = [
];
// Transform the algorithm definitions into the operation-keyed structure
// Also builds a parallel Map<UPPERCASED_NAME, canonicalName> per operation
// for O(1) case-insensitive algorithm name lookup in normalizeAlgorithm.
function createSupportedAlgorithms(algorithmDefs) {
const result = {};
const nameMap = {};
for (const { 0: algorithmName, 1: operations } of ObjectEntries(algorithmDefs)) {
// Skip algorithms that are conditionally not supported
@@ -467,6 +471,8 @@ function createSupportedAlgorithms(algorithmDefs) {
for (const { 0: operation, 1: dict } of ObjectEntries(operations)) {
result[operation] ||= {};
nameMap[operation] ||= new SafeMap();
nameMap[operation].set(StringPrototypeToUpperCase(algorithmName), algorithmName);
// Add experimental warnings for experimental algorithms
if (ArrayPrototypeIncludes(experimentalAlgorithms, algorithmName)) {
@@ -484,10 +490,11 @@ function createSupportedAlgorithms(algorithmDefs) {
}
}
return result;
return { algorithms: result, nameMap };
}
const kSupportedAlgorithms = createSupportedAlgorithms(kAlgorithmDefinitions);
const { algorithms: kSupportedAlgorithms, nameMap: kAlgorithmNameMap } =
createSupportedAlgorithms(kAlgorithmDefinitions);
const simpleAlgorithmDictionaries = {
AesCbcParams: { iv: 'BufferSource' },
@@ -529,6 +536,12 @@ const simpleAlgorithmDictionaries = {
TurboShakeParams: {},
};
// Pre-compute ObjectKeys() for each dictionary entry at module init
// to avoid allocating a new keys array on every normalizeAlgorithm call.
for (const { 0: name, 1: types } of ObjectEntries(simpleAlgorithmDictionaries)) {
simpleAlgorithmDictionaries[name] = { keys: ObjectKeys(types), types };
}
function validateMaxBufferLength(data, name, max = kMaxBufferLength) {
if (data.byteLength > max) {
throw lazyDOMException(
@@ -539,6 +552,14 @@ function validateMaxBufferLength(data, name, max = kMaxBufferLength) {
let webidl;
// Keep this as a regular object. The WebIDL converters read and spread these
// options on the normalizeAlgorithm hot path, and a null-prototype object
// measurably regresses benchmark/misc/webcrypto-webidl normalizeAlgorithm-*.
const kNormalizeAlgorithmOpts = {
prefix: 'Failed to normalize algorithm',
context: 'passed algorithm',
};
// https://w3c.github.io/webcrypto/#algorithm-normalization-normalize-an-algorithm
// adapted for Node.js from Deno's implementation
// https://github.com/denoland/deno/blob/v1.29.1/ext/crypto/00_crypto.js#L195
@@ -551,29 +572,20 @@ function normalizeAlgorithm(algorithm, op) {
// 1.
const registeredAlgorithms = kSupportedAlgorithms[op];
// 2. 3.
const initialAlg = webidl.converters.Algorithm(algorithm, {
prefix: 'Failed to normalize algorithm',
context: 'passed algorithm',
});
const initialAlg = webidl.converters.Algorithm(algorithm,
kNormalizeAlgorithmOpts);
// 4.
let algName = initialAlg.name;
// 5.
let desiredType;
for (const key in registeredAlgorithms) {
if (!ObjectPrototypeHasOwnProperty(registeredAlgorithms, key)) {
continue;
}
if (
StringPrototypeToUpperCase(key) === StringPrototypeToUpperCase(algName)
) {
algName = key;
desiredType = registeredAlgorithms[key];
}
}
if (desiredType === undefined)
// 5. Case-insensitive lookup via pre-built Map (O(1) instead of O(n)).
const canonicalName = kAlgorithmNameMap[op]?.get(
StringPrototypeToUpperCase(algName));
if (canonicalName === undefined)
throw lazyDOMException('Unrecognized algorithm name', 'NotSupportedError');
algName = canonicalName;
const desiredType = registeredAlgorithms[algName];
// Fast path everything below if the registered dictionary is null
if (desiredType === null)
return { name: algName };
@@ -581,39 +593,35 @@ function normalizeAlgorithm(algorithm, op) {
// 6.
const normalizedAlgorithm = webidl.converters[desiredType](
{ __proto__: algorithm, name: algName },
{
prefix: 'Failed to normalize algorithm',
context: 'passed algorithm',
},
kNormalizeAlgorithmOpts,
);
// 7.
normalizedAlgorithm.name = algName;
// 9.
const dict = simpleAlgorithmDictionaries[desiredType];
// 10.
const dictKeys = dict ? ObjectKeys(dict) : [];
for (let i = 0; i < dictKeys.length; i++) {
const member = dictKeys[i];
if (!ObjectPrototypeHasOwnProperty(dict, member))
continue;
const idlType = dict[member];
const idlValue = normalizedAlgorithm[member];
// 3.
if (idlType === 'BufferSource' && idlValue) {
const isView = ArrayBufferIsView(idlValue);
normalizedAlgorithm[member] = TypedArrayPrototypeSlice(
new Uint8Array(
isView ? getDataViewOrTypedArrayBuffer(idlValue) : idlValue,
isView ? getDataViewOrTypedArrayByteOffset(idlValue) : 0,
isView ? getDataViewOrTypedArrayByteLength(idlValue) : ArrayBufferPrototypeGetByteLength(idlValue),
),
);
} else if (idlType === 'HashAlgorithmIdentifier') {
normalizedAlgorithm[member] = normalizeAlgorithm(idlValue, 'digest');
} else if (idlType === 'AlgorithmIdentifier') {
// This extension point is not used by any supported algorithm (yet?)
throw lazyDOMException('Not implemented.', 'NotSupportedError');
// 9. 10. Pre-computed keys and types from simpleAlgorithmDictionaries.
const dictMeta = simpleAlgorithmDictionaries[desiredType];
if (dictMeta) {
const { keys: dictKeys, types: dictTypes } = dictMeta;
for (let i = 0; i < dictKeys.length; i++) {
const member = dictKeys[i];
const idlType = dictTypes[member];
const idlValue = normalizedAlgorithm[member];
// 3.
if (idlType === 'BufferSource' && idlValue) {
const isView = ArrayBufferIsView(idlValue);
normalizedAlgorithm[member] = TypedArrayPrototypeSlice(
new Uint8Array(
isView ? getDataViewOrTypedArrayBuffer(idlValue) : idlValue,
isView ? getDataViewOrTypedArrayByteOffset(idlValue) : 0,
isView ? getDataViewOrTypedArrayByteLength(idlValue) : ArrayBufferPrototypeGetByteLength(idlValue),
),
);
} else if (idlType === 'HashAlgorithmIdentifier') {
normalizedAlgorithm[member] = normalizeAlgorithm(idlValue, 'digest');
} else if (idlType === 'AlgorithmIdentifier') {
// This extension point is not used by any supported algorithm (yet?)
throw lazyDOMException('Not implemented.', 'NotSupportedError');
}
}
}