From 8b52c89b00642d624a5472a0df139593ef82a239 Mon Sep 17 00:00:00 2001 From: Joyee Cheung Date: Sun, 12 Oct 2025 19:47:58 +0200 Subject: [PATCH] benchmark: add benchmark for leaf source text modules PR-URL: https://github.com/nodejs/node/pull/60205 Refs: https://github.com/nodejs/node/issues/59656 Refs: https://github.com/nodejs/node/issues/37648 Reviewed-By: Chengzhong Wu --- benchmark/vm/source-text-module-leaf.js | 84 +++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 benchmark/vm/source-text-module-leaf.js diff --git a/benchmark/vm/source-text-module-leaf.js b/benchmark/vm/source-text-module-leaf.js new file mode 100644 index 0000000000..66d942556c --- /dev/null +++ b/benchmark/vm/source-text-module-leaf.js @@ -0,0 +1,84 @@ +'use strict'; + +const vm = require('vm'); +const common = require('../common.js'); +const assert = require('assert'); + +const bench = common.createBenchmark(main, { + stage: ['all', 'compile', 'link', 'instantiate', 'evaluate'], + type: ['sync', 'async'], + n: [1000], +}, { + flags: ['--experimental-vm-modules'], +}); + +function main({ stage, type, n }) { + const arr = []; + if (stage === 'all' || stage === 'compile') { + bench.start(); + } + + for (let i = 0; i < n; i++) { + let source = `export const value${i} = 1;`; + if (type === 'async') { + source += `\nawait Promise.resolve();\n`; + } + const m = new vm.SourceTextModule(source); + arr.push(m); + } + + if (stage === 'compile') { + bench.end(n); + return; + } + + if (stage === 'link') { + bench.start(); + } + + for (let i = 0; i < n; i++) { + arr[i].linkRequests([]); + } + + if (stage === 'link') { + bench.end(n); + return; + } + + if (stage === 'instantiate') { + bench.start(); + } + + for (let i = 0; i < n; i++) { + arr[i].instantiate(); + } + + if (stage === 'instantiate') { + bench.end(n); + return; + } + + if (stage === 'evaluate') { + bench.start(); + } + + function finalize() { + bench.end(n); + for (let i = 0; i < n; i++) { + assert.strictEqual(arr[i].namespace[`value${i}`], 1); + } + } + + if (type === 'sync') { + for (let i = 0; i < n; i++) { + arr[i].evaluate(); + } + finalize(); + } else { + const promises = []; + for (let i = 0; i < n; i++) { + promises.push(arr[i].evaluate()); + } + Promise.all(promises).then(finalize); + } +}