Skip to content

Commit 0a51aa8

Browse files
Flarnaaddaleax
authored andcommitted
async_hooks: avoid unneeded AsyncResource creation
Inspired by the callstack at #34556 (comment) If the wanted store is equal to the active store it's not needed to create an AsyncResource. Refs: #34556 (comment) PR-URL: #34616 Reviewed-By: Anna Henningsen <[email protected]> Reviewed-By: Stephen Belanger <[email protected]> Reviewed-By: Vladimir de Turckheim <[email protected]> Reviewed-By: Andrey Pechkurov <[email protected]>
1 parent 0af9bee commit 0a51aa8

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

lib/async_hooks.js

+5
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
const {
44
NumberIsSafeInteger,
55
ObjectDefineProperties,
6+
ObjectIs,
67
ReflectApply,
78
Symbol,
89
} = primordials;
@@ -288,6 +289,10 @@ class AsyncLocalStorage {
288289
}
289290

290291
run(store, callback, ...args) {
292+
// Avoid creation of an AsyncResource if store is already active
293+
if (ObjectIs(store, this.getStore())) {
294+
return callback(...args);
295+
}
291296
const resource = new AsyncResource('AsyncLocalStorage');
292297
return resource.runInAsyncScope(() => {
293298
this.enterWith(store);

test/async-hooks/test-async-local-storage-run-resource.js

+15-2
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,21 @@ const asyncLocalStorage = new AsyncLocalStorage();
1010

1111
const outerResource = executionAsyncResource();
1212

13-
asyncLocalStorage.run(new Map(), () => {
14-
assert.notStrictEqual(executionAsyncResource(), outerResource);
13+
const store = new Map();
14+
asyncLocalStorage.run(store, () => {
15+
assert.strictEqual(asyncLocalStorage.getStore(), store);
16+
const innerResource = executionAsyncResource();
17+
assert.notStrictEqual(innerResource, outerResource);
18+
asyncLocalStorage.run(store, () => {
19+
assert.strictEqual(asyncLocalStorage.getStore(), store);
20+
assert.strictEqual(executionAsyncResource(), innerResource);
21+
const otherStore = new Map();
22+
asyncLocalStorage.run(otherStore, () => {
23+
assert.strictEqual(asyncLocalStorage.getStore(), otherStore);
24+
assert.notStrictEqual(executionAsyncResource(), innerResource);
25+
assert.notStrictEqual(executionAsyncResource(), outerResource);
26+
});
27+
});
1528
});
1629

1730
assert.strictEqual(executionAsyncResource(), outerResource);

0 commit comments

Comments
 (0)