2020-08-25 17:05:51 +00:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
const common = require('../common.js');
|
2022-12-16 19:55:42 +00:00
|
|
|
const { createHash } = require('crypto');
|
|
|
|
const { subtle } = globalThis.crypto;
|
2020-08-25 17:05:51 +00:00
|
|
|
|
|
|
|
const bench = common.createBenchmark(main, {
|
|
|
|
sync: ['createHash', 'subtle'],
|
|
|
|
data: [10, 20, 50, 100],
|
|
|
|
method: ['SHA-1', 'SHA-256', 'SHA-384', 'SHA-512'],
|
2023-11-19 06:33:59 +00:00
|
|
|
n: [1e5],
|
2020-08-25 17:05:51 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
const kMethods = {
|
|
|
|
'SHA-1': 'sha1',
|
|
|
|
'SHA-256': 'sha256',
|
|
|
|
'SHA-384': 'sha384',
|
2023-02-10 00:54:53 +00:00
|
|
|
'SHA-512': 'sha512',
|
2020-08-25 17:05:51 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
// This benchmark only looks at clock time and ignores factors
|
|
|
|
// such as event loop delay, event loop utilization, and memory.
|
|
|
|
// As such, it is expected that the synchronous legacy method
|
|
|
|
// will always be faster in clock time.
|
|
|
|
|
|
|
|
function measureLegacy(n, data, method) {
|
|
|
|
method = kMethods[method];
|
|
|
|
bench.start();
|
|
|
|
for (let i = 0; i < n; ++i) {
|
|
|
|
createHash(method).update(data).digest();
|
|
|
|
}
|
|
|
|
bench.end(n);
|
|
|
|
}
|
|
|
|
|
|
|
|
function measureSubtle(n, data, method) {
|
|
|
|
const ec = new TextEncoder();
|
|
|
|
data = ec.encode(data);
|
|
|
|
const jobs = new Array(n);
|
|
|
|
bench.start();
|
|
|
|
for (let i = 0; i < n; i++)
|
|
|
|
jobs[i] = subtle.digest(method, data);
|
|
|
|
Promise.all(jobs).then(() => bench.end(n)).catch((err) => {
|
|
|
|
process.nextTick(() => { throw err; });
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
function main({ n, sync, data, method }) {
|
2022-12-16 19:55:42 +00:00
|
|
|
data = globalThis.crypto.getRandomValues(Buffer.alloc(data));
|
2020-08-25 17:05:51 +00:00
|
|
|
switch (sync) {
|
|
|
|
case 'createHash': return measureLegacy(n, data, method);
|
|
|
|
case 'subtle': return measureSubtle(n, data, method);
|
|
|
|
}
|
|
|
|
}
|