node/benchmark/module/module-require.js
Joyee Cheung 622c3721bf
benchmark: add per-suite setup option
This allows us to set up fixtures for the benchmark suite only
once, which can save quite a bit of time when running benchmarks
that require tens of thousands of fixture files or more (e.g.
the module benchmarks).

PR-URL: https://github.com/nodejs/node/pull/60574
Fixes: https://github.com/nodejs/node/issues/58488
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
Reviewed-By: Rafael Gonzaga <rafael.nunu@hotmail.com>
2025-11-07 17:47:43 +00:00

81 lines
1.7 KiB
JavaScript

'use strict';
const fs = require('fs');
const common = require('../common.js');
const tmpdir = require('../../test/common/tmpdir');
const benchmarkDirectory = tmpdir.resolve('nodejs-benchmark-module');
const bench = common.createBenchmark(main, {
type: ['.js', '.json', 'dir'],
n: [1e4],
}, {
setup(configs) {
tmpdir.refresh();
const maxN = configs.reduce((max, c) => Math.max(max, c.n), 0);
createEntryPoint(maxN);
},
});
function main({ type, n }) {
switch (type) {
case '.js':
measureJSFile(n);
break;
case '.json':
measureJSONFile(n);
break;
case 'dir':
measureDir(n);
}
}
function measureJSFile(n) {
bench.start();
for (let i = 0; i < n; i++) {
require(`${benchmarkDirectory}/${i}`);
}
bench.end(n);
}
function measureJSONFile(n) {
bench.start();
for (let i = 0; i < n; i++) {
require(`${benchmarkDirectory}/json_${i}.json`);
}
bench.end(n);
}
function measureDir(n) {
bench.start();
for (let i = 0; i < n; i++) {
require(`${benchmarkDirectory}${i}`);
}
bench.end(n);
}
function createEntryPoint(n) {
fs.mkdirSync(benchmarkDirectory);
const JSFileContent = 'module.exports = [];';
const JSONFileContent = '[]';
for (let i = 0; i < n; i++) {
// JS file.
fs.writeFileSync(`${benchmarkDirectory}/${i}.js`, JSFileContent);
// JSON file.
fs.writeFileSync(`${benchmarkDirectory}/json_${i}.json`, JSONFileContent);
// Dir.
fs.mkdirSync(`${benchmarkDirectory}${i}`);
fs.writeFileSync(
`${benchmarkDirectory}${i}/package.json`,
'{"main": "index.js"}',
);
fs.writeFileSync(
`${benchmarkDirectory}${i}/index.js`,
JSFileContent,
);
}
}