Skip to content

perf: avoid per-token/line allocations in preprocessor and printer hot paths - #4154

Merged
keith-hall merged 3 commits into
sharkdp:masterfrom
alexander-src:perf/fast-preprocessor-utf8-and-tabs
Nov 27, 2026
Merged

keith-hall merged 3 commits into
sharkdp:masterfrom
alexander-src:perf/fast-preprocessor-utf8-and-tabs

Conversation

@alexander-src

Copy link
Copy Markdown
Contributor

Rendering lines in InteractivePrinter and SimplePrinter allocates several intermediate String buffers per line and per syntax token even when the input is plain ASCII without tabs, ANSI escapes, or control bytes:

  1. expand_tabs, strip_ansi, and sanitize (src/preprocessor.rs) now return Cow<'_, str>, borrowing unchanged slices when no tabs, ANSI introducers (0x1B/0xC2), or sanitize triggers are present, and replacing " ".repeat(spaces) / "─".repeat(...) heap allocations with static slice chunks.
  2. replace_nonprintable (src/preprocessor.rs) replaces byte-by-byte 4-attempt try_parse_utf8_char decoding and un-sized String::new() with input.utf8_chunks(), contiguous printable ASCII (0x21..=0x7E) bulk copies, output.extend(chr.escape_unicode()), and a hex lookup table for invalid bytes.
  3. InteractivePrinter::print_line (src/printer.rs) skips format!("{}{text}", self.ansi_style) and to_reset_sequence() when AnsiStyle::is_empty() is true, hoists line_buf out of the per-region loop in wrapped mode, and takes a fast path for printable ASCII regions that fit within max_width without invoking unicode_segmentation::graphemes or grapheme_width.

Benchmarked over 15 interleaved release-build pairs with oa (oa compare --git master --pairs 15 --check-output) on a 33,000-line Rust source file (~1.1 MiB):

Command master (c3fe1436) This branch Speedup
bat --color=always --paging=never --wrap=character --terminal-width=100 --style=full --language=txt 49.42 ms 26.88 ms 1.80x (95% CI [1.75x, 1.91x], p = 0.0000)
bat --show-all --paging=never --color=never --style=plain 16.44 ms 12.50 ms 1.32x (95% CI [1.31x, 1.33x], p = 0.0000)

Output SHA-256 matched bit-for-bit on both commands (a8ab4305f43e8866 and 1e1c3399360e23f2). cargo fmt --check, cargo clippy --lib -- -D warnings, and cargo test --lib (156 passed) all pass.

Comment thread src/vscreen.rs
Comment on lines +596 to +600
#[inline]
pub(crate) fn has_ansi_introducer(s: &str) -> bool {
s.as_bytes().iter().any(|&b| b == 0x1B || b == 0xC2)
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should this have been put above the comment for is_sequence_introducer, because now the comment is for the wrong method?

@keith-hall keith-hall added this to the v0.26.0 milestone Nov 26, 2026
Comment thread src/vscreen.rs Outdated
/// True for ESC and the 8-bit C1 sequence introducers (DCS/SOS/CSI/OSC/PM/APC).
#[inline]
pub(crate) fn has_ansi_introducer(s: &str) -> bool {
s.as_bytes().iter().any(|&b| b == 0x1B || b == 0xC2)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I asked AI to review this PR and it had the following to say here:

has_ansi_introducer could get its own comment, e.g. “Fast pre-scan for bytes that can start an ANSI/VT escape sequence.”

While here, has_ansi_introducer is currently over-broad: it returns true for any 0xC2, but C1 introducers are only 0xC2 0x90/0x98/0x9B/0x9D/0x9E/0x9F. That means UTF-8 text containing U+0080..U+00BF takes the owned/parse path unnecessarily. A cheap tightening would be:

#[inline]
pub(crate) fn has_ansi_introducer(s: &str) -> bool {
    let bytes = s.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            0x1B => return true,
            0xC2 => {
                if matches!(
                    bytes.get(i + 1),
                    Some(0x90 | 0x98 | 0x9B | 0x9D | 0x9E | 0x9F)
                ) {
                    return true;
                }
            }
            _ => {}
        }
        i += 1;
    }
    false
}

Still a single byte scan, but avoids false positives for common Latin-1-range UTF-8. Could also be worth a small unit test covering "\u{00A9}" (no introducer) vs "\u{009B}31m" (CSI introducer).

Comment thread src/preprocessor.rs Outdated
/// Strips ANSI escape sequences from the input.
pub fn strip_ansi(line: &str) -> String {
/// Strips ANSI escape sequences from the input, borrowing when none are present.
pub fn strip_ansi(line: &str) -> Cow<'_, str> {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as this is a public function, changing the return type deserves a changelog entry detailing the breakage and the migration path please. Same applies to the others as well. (One changelog entry would be fine, but I think important to somehow highlight it as a breaking change for users of bat as an API, and not have it drown amongst the numerous other entries in the changelog. Perhaps it deserves its own section, not sure. Maybe worth checking how breaking changes were communicated previously.)

@alexander-src

Copy link
Copy Markdown
Contributor Author

Thanks @keith-hall, pushed those fixes in 2f68e95:

  • Restored the doc comment above is_sequence_introducer, added a dedicated doc comment for has_ansi_introducer, tightened the 0xC2 check to only the six C1 introducer second bytes (0x90 | 0x98 | 0x9B | 0x9D | 0x9E | 0x9F), and added test_has_ansi_introducer covering "\u{00A9}", other U+0080..U+00BF characters, ESC, and all six C1 introducers.
  • Checked src/lib.rs for the src/preprocessor.rs return types: mod preprocessor; is private, and src/lib.rs only re-exports StripAnsiMode and sanitize_for_terminal (which still returns String). Since expand_tabs, strip_ansi, and sanitize are crate-internal and not reachable by library consumers, changing them to Cow does not break the public API. I narrowed those three functions from pub fn to pub(crate) fn to make that clear, and added a note under ## Other in CHANGELOG.md.

@keith-hall

Copy link
Copy Markdown
Collaborator

Thanks, nice one, looks good. Unfortunately I merged another PR touching the word wrapping code and now there are conflicts. Would you be able to resolve them when you get chance please?

…sor-utf8-and-tabs

# Conflicts:
#	CHANGELOG.md
#	src/printer.rs
#	src/vscreen.rs
@alexander-src

Copy link
Copy Markdown
Contributor Author

Thanks @keith-hall, merged master in 50056ba and resolved the conflicts in src/printer.rs, src/vscreen.rs, and CHANGELOG.md. Guarded the printable-ASCII fast path against pending word_breaks and skip_whitespace from #4140, reused find_sequence_introducer from #4149 inside has_ansi_introducer, and verified cargo fmt, clippy, all 160 lib tests, and all 308 integration tests pass.

@keith-hall
keith-hall merged commit 3f39ff9 into sharkdp:master Nov 27, 2026
24 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants