11cb0ef41Sopenharmony_ci'use strict'; 21cb0ef41Sopenharmony_ci 31cb0ef41Sopenharmony_ciconst common = require('../common.js'); 41cb0ef41Sopenharmony_ciconst { 51cb0ef41Sopenharmony_ci createHash, 61cb0ef41Sopenharmony_ci webcrypto, 71cb0ef41Sopenharmony_ci} = require('crypto'); 81cb0ef41Sopenharmony_ciconst { subtle } = webcrypto; 91cb0ef41Sopenharmony_ci 101cb0ef41Sopenharmony_ciconst bench = common.createBenchmark(main, { 111cb0ef41Sopenharmony_ci sync: ['createHash', 'subtle'], 121cb0ef41Sopenharmony_ci data: [10, 20, 50, 100], 131cb0ef41Sopenharmony_ci method: ['SHA-1', 'SHA-256', 'SHA-384', 'SHA-512'], 141cb0ef41Sopenharmony_ci n: [1e3], 151cb0ef41Sopenharmony_ci}); 161cb0ef41Sopenharmony_ci 171cb0ef41Sopenharmony_ciconst kMethods = { 181cb0ef41Sopenharmony_ci 'SHA-1': 'sha1', 191cb0ef41Sopenharmony_ci 'SHA-256': 'sha256', 201cb0ef41Sopenharmony_ci 'SHA-384': 'sha384', 211cb0ef41Sopenharmony_ci 'SHA-512': 'sha512', 221cb0ef41Sopenharmony_ci}; 231cb0ef41Sopenharmony_ci 241cb0ef41Sopenharmony_ci// This benchmark only looks at clock time and ignores factors 251cb0ef41Sopenharmony_ci// such as event loop delay, event loop utilization, and memory. 261cb0ef41Sopenharmony_ci// As such, it is expected that the synchronous legacy method 271cb0ef41Sopenharmony_ci// will always be faster in clock time. 281cb0ef41Sopenharmony_ci 291cb0ef41Sopenharmony_cifunction measureLegacy(n, data, method) { 301cb0ef41Sopenharmony_ci method = kMethods[method]; 311cb0ef41Sopenharmony_ci bench.start(); 321cb0ef41Sopenharmony_ci for (let i = 0; i < n; ++i) { 331cb0ef41Sopenharmony_ci createHash(method).update(data).digest(); 341cb0ef41Sopenharmony_ci } 351cb0ef41Sopenharmony_ci bench.end(n); 361cb0ef41Sopenharmony_ci} 371cb0ef41Sopenharmony_ci 381cb0ef41Sopenharmony_cifunction measureSubtle(n, data, method) { 391cb0ef41Sopenharmony_ci const ec = new TextEncoder(); 401cb0ef41Sopenharmony_ci data = ec.encode(data); 411cb0ef41Sopenharmony_ci const jobs = new Array(n); 421cb0ef41Sopenharmony_ci bench.start(); 431cb0ef41Sopenharmony_ci for (let i = 0; i < n; i++) 441cb0ef41Sopenharmony_ci jobs[i] = subtle.digest(method, data); 451cb0ef41Sopenharmony_ci Promise.all(jobs).then(() => bench.end(n)).catch((err) => { 461cb0ef41Sopenharmony_ci process.nextTick(() => { throw err; }); 471cb0ef41Sopenharmony_ci }); 481cb0ef41Sopenharmony_ci} 491cb0ef41Sopenharmony_ci 501cb0ef41Sopenharmony_cifunction main({ n, sync, data, method }) { 511cb0ef41Sopenharmony_ci data = webcrypto.getRandomValues(Buffer.alloc(data)); 521cb0ef41Sopenharmony_ci switch (sync) { 531cb0ef41Sopenharmony_ci case 'createHash': return measureLegacy(n, data, method); 541cb0ef41Sopenharmony_ci case 'subtle': return measureSubtle(n, data, method); 551cb0ef41Sopenharmony_ci } 561cb0ef41Sopenharmony_ci} 57