Skip to content

Commit

Permalink
async_hooks: avoid unneeded AsyncResource creation
Browse files Browse the repository at this point in the history
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]>
  • Loading branch information
Flarna authored and codebytere committed Aug 11, 2020
1 parent 0730c76 commit 641a5fb
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
5 changes: 5 additions & 0 deletions lib/async_hooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
const {
NumberIsSafeInteger,
ObjectDefineProperties,
ObjectIs,
ReflectApply,
Symbol,
} = primordials;
Expand Down Expand Up @@ -288,6 +289,10 @@ class AsyncLocalStorage {
}

run(store, callback, ...args) {
// Avoid creation of an AsyncResource if store is already active
if (ObjectIs(store, this.getStore())) {
return callback(...args);
}
const resource = new AsyncResource('AsyncLocalStorage');
return resource.runInAsyncScope(() => {
this.enterWith(store);
Expand Down
17 changes: 15 additions & 2 deletions test/async-hooks/test-async-local-storage-run-resource.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,21 @@ const asyncLocalStorage = new AsyncLocalStorage();

const outerResource = executionAsyncResource();

asyncLocalStorage.run(new Map(), () => {
assert.notStrictEqual(executionAsyncResource(), outerResource);
const store = new Map();
asyncLocalStorage.run(store, () => {
assert.strictEqual(asyncLocalStorage.getStore(), store);
const innerResource = executionAsyncResource();
assert.notStrictEqual(innerResource, outerResource);
asyncLocalStorage.run(store, () => {
assert.strictEqual(asyncLocalStorage.getStore(), store);
assert.strictEqual(executionAsyncResource(), innerResource);
const otherStore = new Map();
asyncLocalStorage.run(otherStore, () => {
assert.strictEqual(asyncLocalStorage.getStore(), otherStore);
assert.notStrictEqual(executionAsyncResource(), innerResource);
assert.notStrictEqual(executionAsyncResource(), outerResource);
});
});
});

assert.strictEqual(executionAsyncResource(), outerResource);

0 comments on commit 641a5fb

Please sign in to comment.