Skip to content

Commit 2ba184c

Browse files
fix(perf): more perf
1 parent 9e9ae4d commit 2ba184c

1 file changed

Lines changed: 20 additions & 19 deletions

File tree

lib/HookCodeFactory.js

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ class HookCodeFactory {
1414
create(options) {
1515
this.init(options);
1616
let fn;
17-
switch (this.options.type) {
17+
switch (options.type) {
1818
case "sync":
1919
fn = new Function(
2020
this.args(),
@@ -91,9 +91,10 @@ class HookCodeFactory {
9191
*/
9292
init(options) {
9393
this.options = options;
94-
// slice() avoids the iterator protocol overhead of [...arr].
95-
// eslint-disable-next-line unicorn/prefer-spread
96-
this._args = options.args.slice();
94+
// `_args` is only read (length / join / [0]) - never mutated - so we
95+
// can share the caller's array directly instead of paying for a copy
96+
// on every compile.
97+
this._args = options.args;
9798
this._joinedArgs = undefined;
9899
}
99100

@@ -454,23 +455,23 @@ class HookCodeFactory {
454455
}
455456

456457
args({ before, after } = {}) {
457-
// Hot during code generation (called once per tap + per interceptor).
458-
// Cache the common no-before/no-after result so we only join once.
459-
if (before === undefined && after === undefined) {
460-
let joined = this._joinedArgs;
461-
if (joined === undefined) {
462-
joined = this._args.length === 0 ? "" : this._args.join(", ");
463-
this._joinedArgs = joined;
464-
}
465-
return joined;
458+
// Hot during code generation. Join `_args` once and cache the result,
459+
// then build the customized variants via string concat instead of
460+
// allocating temporary `[before, ...allArgs]` / `[...allArgs, after]`
461+
// arrays and re-joining.
462+
let joined = this._joinedArgs;
463+
if (joined === undefined) {
464+
joined = this._args.length === 0 ? "" : this._args.join(", ");
465+
this._joinedArgs = joined;
466466
}
467-
let allArgs = this._args;
468-
if (before) allArgs = [before, ...allArgs];
469-
if (after) allArgs = [...allArgs, after];
470-
if (allArgs.length === 0) {
471-
return "";
467+
if (!before && !after) return joined;
468+
if (joined.length === 0) {
469+
if (before && after) return `${before}, ${after}`;
470+
return before || after;
472471
}
473-
return allArgs.join(", ");
472+
if (before && after) return `${before}, ${joined}, ${after}`;
473+
if (before) return `${before}, ${joined}`;
474+
return `${joined}, ${after}`;
474475
}
475476

476477
getTapFn(idx) {

0 commit comments

Comments
 (0)