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)
  • Loading branch information
Flarna committed Aug 4, 2020
1 parent 74df749 commit 5eb30aa
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 @@ -284,6 +285,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 5eb30aa

Please sign in to comment.