From 4eeeab09f02a1b430c8867881ee65b1fdaca0389 Mon Sep 17 00:00:00 2001 From: Joyee Cheung Date: Wed, 9 Oct 2024 16:16:01 +0200 Subject: [PATCH] benchmark: rewrite detect-esm-syntax benchmark Syntax detection has been unflagged so it's no longer meaningful to toggle the detection based on CLI flags. It was also previously benchmarking cached module imports which isn't very meaningful for subsequent loads. This patch updates the benchmark to toggle the detection based on the presence of type field in the package.json, and generates fixtures to benchmark fresh module loads. PR-URL: https://github.com/nodejs/node/pull/55238 Reviewed-By: Yagiz Nizipli Reviewed-By: Matteo Collina --- benchmark/esm/detect-esm-syntax.js | 33 +++++++++++++++--------------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/benchmark/esm/detect-esm-syntax.js b/benchmark/esm/detect-esm-syntax.js index dfc347225f32d6..f12cb46ed77908 100644 --- a/benchmark/esm/detect-esm-syntax.js +++ b/benchmark/esm/detect-esm-syntax.js @@ -4,34 +4,33 @@ // We use the TypeScript fixture because it's a very large CommonJS file with no ESM syntax: the worst case. const common = require('../common.js'); const tmpdir = require('../../test/common/tmpdir.js'); -const fixtures = require('../../test/common/fixtures.js'); -const scriptPath = fixtures.path('snapshot', 'typescript.js'); const fs = require('node:fs'); const bench = common.createBenchmark(main, { - type: ['with-module-syntax-detection', 'without-module-syntax-detection'], + type: ['with-package-json', 'without-package-json'], n: [1e4], -}, { - flags: ['--experimental-detect-module'], }); -const benchmarkDirectory = tmpdir.fileURL('benchmark-detect-esm-syntax'); -const ambiguousURL = new URL('./typescript.js', benchmarkDirectory); -const explicitURL = new URL('./typescript.cjs', benchmarkDirectory); - async function main({ n, type }) { tmpdir.refresh(); + fs.mkdirSync(tmpdir.resolve('bench')); - fs.mkdirSync(benchmarkDirectory, { recursive: true }); - fs.cpSync(scriptPath, ambiguousURL); - fs.cpSync(scriptPath, explicitURL); - - bench.start(); - + let loader = ''; + const modules = []; for (let i = 0; i < n; i++) { - const url = type === 'with-module-syntax-detection' ? ambiguousURL : explicitURL; - await import(url); + const url = tmpdir.fileURL('bench', `mod${i}.js`); + fs.writeFileSync(url, `const foo${i} = ${i};\nexport { foo${i} };\n`); + loader += `import { foo${i} } from './mod${i}.js';\n`; + modules.push(url); } + const loaderURL = tmpdir.fileURL('bench', 'load.js'); + fs.writeFileSync(loaderURL, loader); + if (type === 'with-package-json') { + fs.writeFileSync(tmpdir.resolve('bench', 'package.json'), '{ "type": "module" }'); + } + + bench.start(); + await import(loaderURL); bench.end(n); }