Skip to content

Commit 7680aa1

Browse files
authored
Optimize indent util (#2395)
1 parent 876f9ff commit 7680aa1

File tree

1 file changed

+24
-11
lines changed

1 file changed

+24
-11
lines changed

Diff for: src/util/text.ts

+24-11
Original file line numberDiff line numberDiff line change
@@ -433,22 +433,35 @@ function lookupInUnicodeMap(code: u16, map: u16[]): bool {
433433
return false;
434434
}
435435

436+
/** Creates an indentation matching the number of specified levels. */
436437
const indentX1 = " ";
437438
const indentX2 = " ";
439+
const indentX3 = " ";
438440
const indentX4 = " ";
441+
const indentCache = new Map<i32,string>();
439442

440-
/** Creates an indentation matching the number of specified levels. */
441443
export function indent(sb: string[], level: i32): void {
442-
while (level >= 4) {
443-
sb.push(indentX4);
444-
level -= 4;
445-
}
446-
if (level >= 2) {
447-
sb.push(indentX2);
448-
level -= 2;
449-
}
450-
if (level) {
451-
sb.push(indentX1);
444+
if (level <= 4) {
445+
switch (level) {
446+
case 1: sb.push(indentX1); break;
447+
case 2: sb.push(indentX2); break;
448+
case 3: sb.push(indentX3); break;
449+
case 4: sb.push(indentX4); break;
450+
}
451+
} else {
452+
let indents: string;
453+
// Limit number of indent entries to 1024 for avoiding unnecessary
454+
// memory consumetion
455+
if (indentCache.size <= 1024) {
456+
if (indentCache.has(level)) {
457+
indents = assert(indentCache.get(level));
458+
} else {
459+
indentCache.set(level, (indents = indentX1.repeat(level)));
460+
}
461+
} else {
462+
indents = indentX1.repeat(level);
463+
}
464+
sb.push(indents);
452465
}
453466
}
454467

0 commit comments

Comments
 (0)