Skip to content

Commit d3d4e10

Browse files
apapirovskidanbev
authored andcommitted
async_hooks: improve AsyncResource performance
Accessing symbols is generally quite expensive and so is emitInit, only do both when actually required. PR-URL: #27032 Reviewed-By: Gus Caplan <[email protected]> Reviewed-By: Ruben Bridgewater <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent af03de4 commit d3d4e10

File tree

2 files changed

+15
-15
lines changed

2 files changed

+15
-15
lines changed

lib/async_hooks.js

+14-11
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ const {
2727
emitBefore,
2828
emitAfter,
2929
emitDestroy,
30+
initHooksExist,
3031
} = internal_async_hooks;
3132

3233
// Get symbols
@@ -146,29 +147,31 @@ class AsyncResource {
146147
throw new ERR_INVALID_ASYNC_ID('triggerAsyncId', triggerAsyncId);
147148
}
148149

149-
this[async_id_symbol] = newAsyncId();
150+
const asyncId = newAsyncId();
151+
this[async_id_symbol] = asyncId;
150152
this[trigger_async_id_symbol] = triggerAsyncId;
153+
151154
// This prop name (destroyed) has to be synchronized with C++
152-
this[destroyedSymbol] = { destroyed: false };
155+
const destroyed = { destroyed: false };
156+
this[destroyedSymbol] = destroyed;
153157

154-
emitInit(
155-
this[async_id_symbol], type, this[trigger_async_id_symbol], this
156-
);
158+
if (initHooksExist()) {
159+
emitInit(asyncId, type, triggerAsyncId, this);
160+
}
157161

158162
if (!opts.requireManualDestroy) {
159-
registerDestroyHook(this, this[async_id_symbol], this[destroyedSymbol]);
163+
registerDestroyHook(this, asyncId, destroyed);
160164
}
161165
}
162166

163167
runInAsyncScope(fn, thisArg, ...args) {
164-
emitBefore(this[async_id_symbol], this[trigger_async_id_symbol]);
165-
let ret;
168+
const asyncId = this[async_id_symbol];
169+
emitBefore(asyncId, this[trigger_async_id_symbol]);
166170
try {
167-
ret = Reflect.apply(fn, thisArg, args);
171+
return Reflect.apply(fn, thisArg, args);
168172
} finally {
169-
emitAfter(this[async_id_symbol]);
173+
emitAfter(asyncId);
170174
}
171-
return ret;
172175
}
173176

174177
emitDestroy() {

lib/internal/async_hooks.js

+1-4
Original file line numberDiff line numberDiff line change
@@ -286,14 +286,11 @@ function defaultTriggerAsyncIdScope(triggerAsyncId, block, ...args) {
286286
const oldDefaultTriggerAsyncId = async_id_fields[kDefaultTriggerAsyncId];
287287
async_id_fields[kDefaultTriggerAsyncId] = triggerAsyncId;
288288

289-
let ret;
290289
try {
291-
ret = Reflect.apply(block, null, args);
290+
return Reflect.apply(block, null, args);
292291
} finally {
293292
async_id_fields[kDefaultTriggerAsyncId] = oldDefaultTriggerAsyncId;
294293
}
295-
296-
return ret;
297294
}
298295

299296

0 commit comments

Comments
 (0)