Created
June 17, 2023 00:09
-
-
Save zynaxsoft/c26f9e2e08be2d5315203e172596d5ab to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::collections::VecDeque; | |
use std::time::Instant; | |
macro_rules! dump_screen_old { | |
($lines:expr) => {{ | |
let mut is_first = true; | |
let mut buf = "".to_owned(); | |
for line in &$lines { | |
if line.is_canonical && !is_first { | |
buf.push_str("\n"); | |
} | |
let s: String = (&line.columns).into_iter().map(|x| x.character).collect(); | |
// Replace the spaces at the end of the line. Sometimes, the lines are | |
// collected with spaces until the end of the panel. | |
let re = regex::Regex::new("([^ ])[ ]*$").unwrap(); | |
buf.push_str(&(re.replace(&s, "${1}"))); | |
is_first = false; | |
} | |
buf | |
}}; | |
} | |
macro_rules! dump_screen_new { | |
($lines:expr) => {{ | |
let mut is_first = true; | |
let mut buf = String::with_capacity($lines.iter().map(|l| l.len()).sum()); | |
for line in &$lines { | |
if line.is_canonical && !is_first { | |
buf.push_str("\n"); | |
} | |
let s: String = (&line.columns).into_iter().map(|x| x.character).collect(); | |
// Replace the spaces at the end of the line. Sometimes, the lines are | |
// collected with spaces until the end of the panel. | |
buf.push_str(&s.trim_end_matches(' ')); | |
is_first = false; | |
} | |
buf | |
}}; | |
} | |
#[derive(Clone, Copy, PartialEq)] | |
pub struct TerminalCharacter { | |
pub character: char, | |
} | |
#[derive(Clone)] | |
pub struct Row { | |
pub columns: VecDeque<TerminalCharacter>, | |
pub is_canonical: bool, | |
} | |
impl Row { | |
pub fn len(&self) -> usize { | |
self.columns.len() | |
} | |
} | |
fn main() { | |
let mut scroll_back = VecDeque::new(); | |
let mut columns = VecDeque::new(); | |
columns.push_back(TerminalCharacter { character: 'y' }); | |
columns.push_back(TerminalCharacter { character: '\n' }); | |
let row = Row { | |
columns, | |
is_canonical: false, | |
}; | |
for _ in 1..1_000_000 { | |
scroll_back.push_back(row.clone()) | |
} | |
let now = Instant::now(); | |
{ | |
dump_screen_old!(scroll_back); | |
} | |
let elapsed = now.elapsed(); | |
println!("Old method: {elapsed:.2?}"); | |
let now = Instant::now(); | |
{ | |
dump_screen_new!(scroll_back); | |
} | |
let elapsed = now.elapsed(); | |
println!("New method: {elapsed:.2?}"); | |
println!("Done"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Old method: 7.55s
New method: 16.72ms
Done