From c2e83bf801770cfa85f48ef6d4a1e5fae6e559e3 Mon Sep 17 00:00:00 2001 From: Chengzhong Wu Date: Mon, 8 Dec 2025 12:19:55 +0000 Subject: [PATCH] benchmark: add microbench on isInsideNodeModules --- .../internal/util_isinsidenodemodules.js | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 benchmark/internal/util_isinsidenodemodules.js diff --git a/benchmark/internal/util_isinsidenodemodules.js b/benchmark/internal/util_isinsidenodemodules.js new file mode 100644 index 00000000000000..bb6746db93f339 --- /dev/null +++ b/benchmark/internal/util_isinsidenodemodules.js @@ -0,0 +1,52 @@ +'use strict'; +const common = require('../common.js'); +const assert = require('assert'); + +const bench = common.createBenchmark(main, { + n: [1e6], + stackLimit: [100], + stackCount: [99, 101], + method: ['isInsideNodeModules', 'noop'], +}, { + flags: ['--expose-internals', '--disable-warning=internal/test/binding'], +}); + +function main({ n, stackLimit, stackCount, method }) { + const { internalBinding } = require('internal/test/binding'); + const { isInsideNodeModules } = internalBinding('util'); + + const testFunction = method === 'noop' ? + () => { + bench.start(); + for (let i = 0; i < n; i++) { + noop(); + } + bench.end(n); + } : + () => { + Error.stackTraceLimit = Infinity; + const existingStackFrameCount = new Error().stack.split('\n').length - 1; + assert.strictEqual(existingStackFrameCount, stackCount); + + bench.start(); + for (let i = 0; i < n; i++) { + isInsideNodeModules(stackLimit, true); + } + bench.end(n); + }; + + // Excluding the message line. + const existingStackFrameCount = new Error().stack.split('\n').length - 1; + // Excluding the test function itself. + nestCallStack(stackCount - existingStackFrameCount - 1, testFunction); +} + +function nestCallStack(depth, callback) { + // nestCallStack(1) already adds a stack frame, so we stop at 1. + if (depth === 1) { + return callback(); + } + return nestCallStack(depth - 1, callback); +} + +function noop() {}