mirror of
https://github.com/nodejs/node.git
synced 2024-11-21 10:59:27 +00:00
4c46439fe9
This patch introduces a helper crypto.hash() that computes a digest from the input at one shot. This can be 1.2-1.6x faster than the object-based createHash() for smaller inputs (<= 5MB) that are readily available (not streamed) and incur less memory overhead since no intermediate objects will be created. PR-URL: https://github.com/nodejs/node/pull/51044 Refs: https://github.com/nodejs/performance/issues/136 Reviewed-By: Vinícius Lourenço Claro Cardoso <contact@viniciusl.com.br> Reviewed-By: Yagiz Nizipli <yagiz.nizipli@sentry.io>
43 lines
1.1 KiB
JavaScript
43 lines
1.1 KiB
JavaScript
'use strict';
|
|
|
|
const common = require('../common.js');
|
|
const { createHash, hash } = require('crypto');
|
|
const path = require('path');
|
|
const filepath = path.resolve(__dirname, '../../test/fixtures/snapshot/typescript.js');
|
|
const fs = require('fs');
|
|
const assert = require('assert');
|
|
|
|
const bench = common.createBenchmark(main, {
|
|
length: [1000, 100_000],
|
|
method: ['md5', 'sha1', 'sha256'],
|
|
type: ['string', 'buffer'],
|
|
n: [100_000, 1000],
|
|
}, {
|
|
combinationFilter: ({ length, n }) => {
|
|
return length * n <= 100_000 * 1000;
|
|
},
|
|
});
|
|
|
|
function main({ length, type, method, n }) {
|
|
let data = fs.readFileSync(filepath);
|
|
if (type === 'string') {
|
|
data = data.toString().slice(0, length);
|
|
} else {
|
|
data = Uint8Array.prototype.slice.call(data, 0, length);
|
|
}
|
|
|
|
const oneshotHash = hash ?
|
|
(method, input) => hash(method, input, 'hex') :
|
|
(method, input) => createHash(method).update(input).digest('hex');
|
|
const array = [];
|
|
for (let i = 0; i < n; i++) {
|
|
array.push(null);
|
|
}
|
|
bench.start();
|
|
for (let i = 0; i < n; i++) {
|
|
array[i] = oneshotHash(method, data);
|
|
}
|
|
bench.end(n);
|
|
assert.strictEqual(typeof array[n - 1], 'string');
|
|
}
|