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 <anna@addaleax.net>
Reviewed-By: Stephen Belanger <admin@stephenbelanger.com>
Reviewed-By: Vladimir de Turckheim <vlad2t@hotmail.com>
Reviewed-By: Andrey Pechkurov <apechkurov@gmail.com>
  • Loading branch information
Flarna authored and addaleax committed Sep 22, 2020
1 parent 07968ac commit 0a44017
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
Expand Up @@ -3,6 +3,7 @@
const {
NumberIsSafeInteger,
ObjectDefineProperties,
ObjectIs,
ReflectApply,
Symbol,
} = primordials;
Expand Down Expand Up @@ -285,6 +286,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
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 0a44017

Please sign in to comment.