From b2837ff3bea286ce7ccfba9b6fbcd861977caf83 Mon Sep 17 00:00:00 2001 From: Gokul Soumya Date: Sat, 24 Dec 2022 16:51:38 +0530 Subject: Minimize allocation when converting table rows to string --- helix-tui/src/text.rs | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) (limited to 'helix-tui/src/text.rs') diff --git a/helix-tui/src/text.rs b/helix-tui/src/text.rs index 6970634b..a3e242fe 100644 --- a/helix-tui/src/text.rs +++ b/helix-tui/src/text.rs @@ -438,17 +438,30 @@ impl<'a> From>> for Text<'a> { impl<'a> From> for String { fn from(text: Text<'a>) -> String { - let lines: Vec = text.lines.iter().map(String::from).collect(); - lines.join("\n") + String::from(&text) } } impl<'a> From<&Text<'a>> for String { fn from(text: &Text<'a>) -> String { - let lines: Vec = text.lines.iter().map(String::from).collect(); - lines.join("\n") + let size = text + .lines + .iter() + .flat_map(|spans| spans.0.iter().map(|span| span.content.len())) + .sum::() + + text.lines.len().saturating_sub(1); // for newline after each line + let mut output = String::with_capacity(size); + + for spans in &text.lines { + for span in &spans.0 { + output.push_str(&span.content); + } + output.push('\n'); + } + output } } + impl<'a> IntoIterator for Text<'a> { type Item = Spans<'a>; type IntoIter = std::vec::IntoIter; -- cgit v1.2.3-70-g09d2