From 0bcb9d8603645d8eb50590f620d82faee5cc63c8 Mon Sep 17 00:00:00 2001 From: Ilyas Shabi Date: Thu, 3 Dec 2026 15:53:50 +0100 Subject: [PATCH] process: skip AsyncResource in queueMicrotask when only ALS is active Signed-off-by: Ilyas Shabi --- benchmark/process/queue-microtask-breadth.js | 13 ++++++++++++- benchmark/process/queue-microtask-depth.js | 13 ++++++++++++- lib/internal/process/task_queues.js | 5 ++--- 3 files changed, 26 insertions(+), 5 deletions(-) diff --git a/benchmark/process/queue-microtask-breadth.js b/benchmark/process/queue-microtask-breadth.js index c0c30a67b7e6..2802b3404fe6 100644 --- a/benchmark/process/queue-microtask-breadth.js +++ b/benchmark/process/queue-microtask-breadth.js @@ -3,9 +3,20 @@ const common = require('../common.js'); const bench = common.createBenchmark(main, { n: [4e5], + als: [0, 1], }); -function main({ n }) { +function main({ n, als }) { + if (als) { + const { AsyncLocalStorage } = require('async_hooks'); + // Run the benchmark inside an AsyncLocalStorage context + new AsyncLocalStorage().run({}, () => queue(n)); + } else { + queue(n); + } +} + +function queue(n) { let j = 0; function cb() { diff --git a/benchmark/process/queue-microtask-depth.js b/benchmark/process/queue-microtask-depth.js index e45c00d2c71a..136f2e0c9b56 100644 --- a/benchmark/process/queue-microtask-depth.js +++ b/benchmark/process/queue-microtask-depth.js @@ -2,9 +2,20 @@ const common = require('../common.js'); const bench = common.createBenchmark(main, { n: [12e5], + als: [0, 1], }); -function main({ n }) { +function main({ n, als }) { + if (als) { + const { AsyncLocalStorage } = require('async_hooks'); + // Run the benchmark inside an AsyncLocalStorage context. + new AsyncLocalStorage().run({}, () => start(n)); + } else { + start(n); + } +} + +function start(n) { let counter = n; bench.start(); queueMicrotask(onNextTick); diff --git a/lib/internal/process/task_queues.js b/lib/internal/process/task_queues.js index c3f935cae389..8dff4fed189f 100644 --- a/lib/internal/process/task_queues.js +++ b/lib/internal/process/task_queues.js @@ -167,8 +167,7 @@ const defaultMicrotaskResourceOpts = { requireManualDestroy: true }; function queueMicrotask(callback) { validateFunction(callback, 'callback'); - const contextFrame = AsyncContextFrame.current(); - if (contextFrame || enabledHooksExist()) { + if (enabledHooksExist()) { const asyncResource = new AsyncResource( 'Microtask', defaultMicrotaskResourceOpts, @@ -176,7 +175,7 @@ function queueMicrotask(callback) { asyncResource.callback = callback; enqueueMicrotask(FunctionPrototypeBind(runMicrotask, asyncResource)); } else { - // Fast path: no AsyncLocalStorage in use + // Fast path: V8's CallableTask preserves ContinuationPreservedEmbedderData. enqueueMicrotask(callback); } }