Hasty Briefsbeta

Bilingual

Why stdout is faster than stderr? (2024)

2 days ago
  • #rust
  • #performance
  • #terminal
  • stdout in Rust is faster than stderr due to stdout being line-buffered by default (using LineWriter) while stderr is unbuffered (raw).
  • Buffering reduces the number of system calls: line-buffered stdout flushes on newline, while unbuffered stderr writes immediately, causing more frequent and slower writes.
  • Experiments with TUI applications using ratatui and crossterm show that applying line buffering to stderr (via LineWriter) makes its performance similar to stdout.
  • Raw/unbuffered stdout (achieved via unsafe file descriptor manipulation) performs similarly to raw stderr, confirming buffering is key to performance differences.
  • Other languages like Python and C also use buffered I/O for stdout, while languages like Go and Zig default to unbuffered streams, allowing manual buffering for optimization.