Skip to content

Commit 1904053

Browse files
authored
perf(compiler-core): use binary-search to get line and column (#14222)
1 parent f5b3bf2 commit 1904053

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

packages/compiler-core/src/tokenizer.ts

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -296,14 +296,30 @@ export default class Tokenizer {
296296
public getPos(index: number): Position {
297297
let line = 1
298298
let column = index + 1
299-
for (let i = this.newlines.length - 1; i >= 0; i--) {
300-
const newlineIndex = this.newlines[i]
301-
if (index > newlineIndex) {
302-
line = i + 2
303-
column = index - newlineIndex
304-
break
299+
const length = this.newlines.length
300+
let j = -1
301+
if (length > 100) {
302+
let l = -1
303+
let r = length
304+
while (l + 1 < r) {
305+
const m = (l + r) >>> 1
306+
this.newlines[m] < index ? (l = m) : (r = m)
307+
}
308+
j = l
309+
} else {
310+
for (let i = length - 1; i >= 0; i--) {
311+
if (index > this.newlines[i]) {
312+
j = i
313+
break
314+
}
305315
}
306316
}
317+
318+
if (j >= 0) {
319+
line = j + 2
320+
column = index - this.newlines[j]
321+
}
322+
307323
return {
308324
column,
309325
line,

0 commit comments

Comments
 (0)