From 2e71c1874e2de6d9f2bd21622246e55484a9fc62 Mon Sep 17 00:00:00 2001 From: EdJoPaTo Date: Sun, 21 Apr 2024 19:29:37 +0200 Subject: [PATCH] perf(buffer): simplify Buffer::filled with macro (#1036) The `vec![]` macro is highly optimized by the Rust team and shorter. Don't do it manually. This change is mainly cleaner code. The only production code that uses this is `Terminal::with_options` and `Terminal::insert_before` so it's not performance relevant on every render. --- benches/block.rs | 19 +++++++++---------- src/buffer/buffer.rs | 11 +++++------ 2 files changed, 14 insertions(+), 16 deletions(-) diff --git a/benches/block.rs b/benches/block.rs index aaca9b2b..03b61bd2 100644 --- a/benches/block.rs +++ b/benches/block.rs @@ -1,8 +1,7 @@ -use criterion::{criterion_group, criterion_main, BatchSize, Bencher, BenchmarkId, Criterion}; +use criterion::{criterion_group, criterion_main, BatchSize, Bencher, Criterion}; use ratatui::{ buffer::Buffer, - layout::Rect, - prelude::Alignment, + layout::{Alignment, Rect}, widgets::{ block::{Position, Title}, Block, Borders, Padding, Widget, @@ -13,23 +12,23 @@ use ratatui::{ fn block(c: &mut Criterion) { let mut group = c.benchmark_group("block"); - for buffer_size in [ - Rect::new(0, 0, 100, 50), // vertically split screen - Rect::new(0, 0, 200, 50), // 1080p fullscreen with medium font - Rect::new(0, 0, 256, 256), // Max sized area + for (width, height) in [ + (100, 50), // vertically split screen + (200, 50), // 1080p fullscreen with medium font + (256, 256), // Max sized area ] { - let buffer_area = buffer_size.area(); + let buffer_size = Rect::new(0, 0, width, height); // Render an empty block group.bench_with_input( - BenchmarkId::new("render_empty", buffer_area), + format!("render_empty/{width}x{height}"), &Block::new(), |b, block| render(b, block, buffer_size), ); // Render with all features group.bench_with_input( - BenchmarkId::new("render_all_feature", buffer_area), + format!("render_all_feature/{width}x{height}"), &Block::new() .borders(Borders::ALL) .title("test title") diff --git a/src/buffer/buffer.rs b/src/buffer/buffer.rs index 9cfa848f..9262b51d 100644 --- a/src/buffer/buffer.rs +++ b/src/buffer/buffer.rs @@ -55,22 +55,21 @@ pub struct Buffer { impl Buffer { /// Returns a Buffer with all cells set to the default one + #[must_use] pub fn empty(area: Rect) -> Self { - let cell = Cell::default(); - Self::filled(area, &cell) + Self::filled(area, &Cell::default()) } /// Returns a Buffer with all cells initialized with the attributes of the given Cell + #[must_use] pub fn filled(area: Rect, cell: &Cell) -> Self { let size = area.area() as usize; - let mut content = Vec::with_capacity(size); - for _ in 0..size { - content.push(cell.clone()); - } + let content = vec![cell.clone(); size]; Self { area, content } } /// Returns a Buffer containing the given lines + #[must_use] pub fn with_lines<'a, Iter>(lines: Iter) -> Self where Iter: IntoIterator,