async_hooks: avoid unneeded AsyncResource creation

Inspired by the callstack at https://github.com/nodejs/node/issues/34556#issuecomment-666743528

If the wanted store is equal to the active store it's not needed to
create an AsyncResource.

Refs: https://github.com/nodejs/node/issues/34556#issuecomment-666743528

PR-URL: https://github.com/nodejs/node/pull/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>
This commit is contained in:
Gerhard Stoebich 2020-08-03 23:19:54 +02:00
parent e43bb2f101
commit 48249889b6
2 changed files with 20 additions and 2 deletions

View File

@ -3,6 +3,7 @@
const {
NumberIsSafeInteger,
ObjectDefineProperties,
ObjectIs,
ReflectApply,
Symbol,
} = primordials;
@ -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);

View File

@ -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);