Skip to content

Commit 0848ebc

Browse files
committed
Greatly speed up encoding
1 parent 0adb3a2 commit 0848ebc

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

src/encode/encoder.ts

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,10 @@ export class Encoder {
3131
readonly #info: ScopeInfo;
3232
readonly #names: string[];
3333

34+
// Hash map to resolve indices of strings in the "names" array. Otherwise we'd have
35+
// to use 'indexOf' for every name we want to encode.
36+
readonly #namesToIndex = new Map<string, number>();
37+
3438
readonly #scopeState = { ...DEFAULT_SCOPE_STATE };
3539
readonly #rangeState = { ...DEFAULT_RANGE_STATE };
3640
#encodedItems: string[] = [];
@@ -42,6 +46,10 @@ export class Encoder {
4246
constructor(info: ScopeInfo, names: string[]) {
4347
this.#info = info;
4448
this.#names = names;
49+
50+
for (let i = 0; i < names.length; ++i) {
51+
this.#namesToIndex.set(names[i], i);
52+
}
4553
}
4654

4755
encode(): string {
@@ -223,11 +231,13 @@ export class Encoder {
223231
}
224232

225233
#resolveNamesIdx(name: string): number {
226-
const index = this.#names.indexOf(name);
227-
if (index >= 0) return index;
234+
const index = this.#namesToIndex.get(name);
235+
if (index !== undefined) return index;
228236

237+
const addedIndex = this.#names.length;
229238
this.#names.push(name);
230-
return this.#names.length - 1;
239+
this.#namesToIndex.set(name, addedIndex);
240+
return addedIndex;
231241
}
232242

233243
#verifyPositionWithScopeState(line: number, column: number) {

0 commit comments

Comments
 (0)