I am using tokio
to copy a file (tokio::fs::File
) to a socket (tokio::net::TcpStream
):
let mut buf = [0; 1024];
while let Ok(n) = file.read(&mut buf[..]).await {
if n == 0 {
break;
}
socket.write(&buf[..n]).await?;
}
But I noticed that this code runs much faster:
tokio::io::copy(&mut file, &mut socket).await?;
Even when the buffer size is the same, the copy_buf
call is still much faster:
tokio::io::copy_buf(&mut tokio::io::BufReader::with_capacity(1024, &mut file), &mut socket).await?;
Why? How could I optimize the first code block?