Skip to content

Commit 326045f

Browse files
committed
perf: allocate less when printing
For example, instead of `collect`ing chars into a `String` and then `write`-ing that, `write` each char individually
1 parent 4fc236e commit 326045f

File tree

1 file changed

+18
-19
lines changed

1 file changed

+18
-19
lines changed

crates/vim9-lexer/src/lib.rs

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
use std::{
44
cell::{Cell, RefCell},
55
collections::VecDeque,
6-
fmt::{Debug, Display},
6+
fmt::{Debug, Display, Write},
77
};
88

99
use anyhow::{Context, Result};
@@ -79,15 +79,16 @@ impl Debug for TokenText<'_> {
7979

8080
impl Display for TokenText<'_> {
8181
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82-
write!(
83-
f,
84-
"{}",
85-
match self {
86-
TokenText::Slice(s) => s.iter().collect::<String>(),
87-
TokenText::Owned(s) => s.clone(),
88-
TokenText::Empty => "".to_string(),
82+
match self {
83+
TokenText::Slice(s) => {
84+
for c in *s {
85+
f.write_char(*c)?;
86+
}
87+
Ok(())
8988
}
90-
)
89+
TokenText::Owned(s) => write!(f, "{s}"),
90+
TokenText::Empty => Ok(()),
91+
}
9192
}
9293
}
9394

@@ -102,10 +103,7 @@ impl<'a> TokenText<'a> {
102103

103104
pub fn equals(&self, val: &str) -> bool {
104105
match self {
105-
TokenText::Slice(s) => {
106-
// This seems like I shouldn't have to do this... oh well
107-
val.chars().collect::<Vec<char>>() == *s
108-
}
106+
TokenText::Slice(s) => s.iter().copied().eq(val.chars()),
109107
TokenText::Owned(s) => s.as_str() == val,
110108
TokenText::Empty => false,
111109
}
@@ -1054,8 +1052,7 @@ pub fn snapshot_lexing(input: &str) -> String {
10541052

10551053
let mut output = String::new();
10561054
for (row, line) in input.lines().enumerate() {
1057-
output += line;
1058-
output += "\n";
1055+
let _ = writeln!(output, "{line}");
10591056

10601057
while let Some(tok) = tokens.pop_front() {
10611058
if tok.span.start_row != tok.span.end_row {
@@ -1067,10 +1064,12 @@ pub fn snapshot_lexing(input: &str) -> String {
10671064
break;
10681065
}
10691066

1070-
output += &" ".repeat(tok.span.start_col);
1071-
output += &"^".repeat(tok.span.end_col - tok.span.start_col);
1072-
output += &format!(" {tok:?}");
1073-
output += "\n"
1067+
let _ = writeln!(
1068+
output,
1069+
"{indent}{span} {tok:?}",
1070+
indent = " ".repeat(tok.span.start_col),
1071+
span = "^".repeat(tok.span.end_col - tok.span.start_col),
1072+
);
10741073
}
10751074
}
10761075

0 commit comments

Comments
 (0)