Skip to content

Commit 78367b7

Browse files
committed
perf: introduce last_searched_chunk_idx to speed up searching
1 parent 5be6ea7 commit 78367b7

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

src/magic_string/mod.rs

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ pub struct MagicString<'s> {
3434
chunk_by_start: FxHashMap<TextSize, ChunkIdx>,
3535
chunk_by_end: FxHashMap<TextSize, ChunkIdx>,
3636
guessed_indentor: OnceCell<String>,
37+
38+
// This is used to speed up the search for the chunk that contains a given index.
39+
last_searched_chunk_idx: ChunkIdx,
3740
}
3841

3942
impl<'text> MagicString<'text> {
@@ -62,6 +65,7 @@ impl<'text> MagicString<'text> {
6265
// setup options
6366
filename: options.filename,
6467
guessed_indentor: OnceCell::default(),
68+
last_searched_chunk_idx: initial_chunk_idx,
6569
};
6670

6771
magic_string.chunk_by_start.insert(0, initial_chunk_idx);
@@ -213,12 +217,13 @@ impl<'text> MagicString<'text> {
213217
return;
214218
}
215219

216-
let (mut candidate, mut candidate_idx, search_right) =
217-
if (self.source_len - at_index) > at_index {
218-
(self.first_chunk(), self.first_chunk_idx, true)
219-
} else {
220-
(self.last_chunk(), self.last_chunk_idx, false)
221-
};
220+
let (mut candidate, mut candidate_idx, search_right) = {
221+
let last_searched_chunk = &self.chunks[self.last_searched_chunk_idx];
222+
let search_right = at_index > last_searched_chunk.end();
223+
224+
(last_searched_chunk, self.last_searched_chunk_idx, search_right)
225+
};
226+
222227

223228
while !candidate.contains(at_index) {
224229
let next_idx = if search_right {

0 commit comments

Comments
 (0)