1'use strict'; 2 3const common = require('../common.js'); 4const { 5 createHash, 6 webcrypto, 7} = require('crypto'); 8const { subtle } = webcrypto; 9 10const bench = common.createBenchmark(main, { 11 sync: ['createHash', 'subtle'], 12 data: [10, 20, 50, 100], 13 method: ['SHA-1', 'SHA-256', 'SHA-384', 'SHA-512'], 14 n: [1e3], 15}); 16 17const kMethods = { 18 'SHA-1': 'sha1', 19 'SHA-256': 'sha256', 20 'SHA-384': 'sha384', 21 'SHA-512': 'sha512', 22}; 23 24// This benchmark only looks at clock time and ignores factors 25// such as event loop delay, event loop utilization, and memory. 26// As such, it is expected that the synchronous legacy method 27// will always be faster in clock time. 28 29function measureLegacy(n, data, method) { 30 method = kMethods[method]; 31 bench.start(); 32 for (let i = 0; i < n; ++i) { 33 createHash(method).update(data).digest(); 34 } 35 bench.end(n); 36} 37 38function measureSubtle(n, data, method) { 39 const ec = new TextEncoder(); 40 data = ec.encode(data); 41 const jobs = new Array(n); 42 bench.start(); 43 for (let i = 0; i < n; i++) 44 jobs[i] = subtle.digest(method, data); 45 Promise.all(jobs).then(() => bench.end(n)).catch((err) => { 46 process.nextTick(() => { throw err; }); 47 }); 48} 49 50function main({ n, sync, data, method }) { 51 data = webcrypto.getRandomValues(Buffer.alloc(data)); 52 switch (sync) { 53 case 'createHash': return measureLegacy(n, data, method); 54 case 'subtle': return measureSubtle(n, data, method); 55 } 56} 57