Why printing to console is expensive?

⚓ Rust    📅 2025-07-24    👤 surdeus    👁️ 4      

surdeus

Hello everyone,

I'm currently developing a network application and working with a buffer vector of approximately 2MB in size. I'm reading data from the network, converting it into a String, and then printing it to the console.

However, I've noticed that the printing operation is taking a significant amount of time even it only prints a few data (around 1 or 2 seconds).

Below is a snippet of the relevant code. I have a few questions regarding this behavior and would appreciate your insights:

    let mut buffer = vec![0; 1024 * 1024 * 2];

    let bytes_cnt = socket.read(&mut buffer).await?;
    if bytes_cnt.eq(&0) {
        return Err(anyhow::anyhow!("Client sent zero length data."));
    }

    // Is this method good for shrinking vector?
    // let buffer = Vec::from(&buffer[0..bytes_cnt]);

    let buffer_str = String::from_utf8(buffer).unwrap_or_default();

    // It is taking too long time when you print 2MB data to terminal.
    tracing::info!(
        "received {} bytes, buffer_str: {}",
        bytes_cnt,
        buffer_str
    );

My questions:

  1. Why printing to terminal is expensive?
  2. What is the best way of shrinking vector?
  3. Is String::from_utf8 function best for converting Vec<u8>?

Thanks to all.

3 posts - 2 participants

Read full topic

🏷️ Rust_feed