Skip to content

Commit 285aa05

Browse files
committed
perf: avoid +1 a lot of time by changing startIdx to 1
1 parent 208262c commit 285aa05

File tree

1 file changed

+12
-11
lines changed

1 file changed

+12
-11
lines changed

src/compiler.ts

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ function compileRouteMatch(ctx: CompilerContext): string {
9696
}
9797
}
9898

99-
const match = compileNode(ctx, ctx.router.root, [], 0);
99+
const match = compileNode(ctx, ctx.router.root, [], 1);
100100
// Empty root node emit an empty bound check
101101
if (match) {
102102
code += `let s=p.split("/"),l=s.length;${match}`;
@@ -182,7 +182,7 @@ function compileNode(
182182
ctx: CompilerContext,
183183
node: Node<any>,
184184
params: string[],
185-
startIdx: number,
185+
currentIdx: number,
186186
): string {
187187
const hasLastOptionalParam = node.key === "*";
188188
let code = "",
@@ -193,10 +193,10 @@ function compileNode(
193193
ctx,
194194
node.methods,
195195
params,
196-
hasLastOptionalParam ? startIdx : -1,
196+
hasLastOptionalParam ? currentIdx - 1 : -1,
197197
);
198198
if (match) {
199-
code += `if(l===${startIdx + 1}${hasLastOptionalParam ? `||l===${startIdx}` : ""}){${match}}`;
199+
code += `if(l===${currentIdx}${hasLastOptionalParam ? `||l===${currentIdx - 1}` : ""}){${match}}`;
200200
hasIf = true;
201201
}
202202
}
@@ -206,25 +206,26 @@ function compileNode(
206206
const notNeedBoundCheck = hasIf;
207207

208208
for (const key in node.static) {
209-
const match = compileNode(ctx, node.static[key], params, startIdx + 1);
209+
const match = compileNode(ctx, node.static[key], params, currentIdx + 1);
210210
if (match) {
211-
staticCode += `${hasIf ? "else " : ""}if(s[${startIdx + 1}]===${JSON.stringify(key)}){${match}}`;
211+
staticCode += `${hasIf ? "else " : ""}if(s[${currentIdx}]===${JSON.stringify(key)}){${match}}`;
212212
hasIf = true;
213213
}
214214
}
215215

216216
if (staticCode)
217217
code += notNeedBoundCheck
218218
? staticCode
219-
: `if(l>${startIdx + 1}){${staticCode}}`;
219+
: `if(l>${currentIdx}){${staticCode}}`;
220220
}
221221

222222
if (node.param) {
223223
code += compileNode(
224224
ctx,
225225
node.param,
226-
params.concat(`s[${startIdx + 1}]`),
227-
startIdx + 1,
226+
// Prevent deopt
227+
params.concat(`s[${currentIdx}]`),
228+
currentIdx + 1,
228229
);
229230
}
230231

@@ -238,8 +239,8 @@ function compileNode(
238239
code += compileMethodMatch(
239240
ctx,
240241
wildcard.methods,
241-
params.concat(`s.slice(${startIdx + 1}).join('/')`),
242-
startIdx,
242+
params.concat(`s.slice(${currentIdx}).join('/')`),
243+
currentIdx,
243244
);
244245
}
245246
}

0 commit comments

Comments
 (0)