Skip to content

Commit

Permalink
perf(buffer): simplify Buffer::filled with macro (#1036)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
EdJoPaTo committed Apr 21, 2024
1 parent c75aa19 commit 2e71c18
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 16 deletions.
19 changes: 9 additions & 10 deletions 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,
Expand All @@ -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")
Expand Down
11 changes: 5 additions & 6 deletions src/buffer/buffer.rs
Expand Up @@ -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,
Expand Down

0 comments on commit 2e71c18

Please sign in to comment.