If I recall correctly, println
locks stdout. Taken from Rust Performance Pitfalls:
[...] the default print!
macros will lock STDOUT for each write operation. So if you have a larger textual output (or input from STDIN), you should lock manually.
This:
let mut out = File::new("test.out");
println!("{}", header);
for line in lines {
println!("{}", line);
writeln!(out, "{}", line);
}
println!("{}", footer);
locks and unlocks io::stdout a lot, and does a linear number of (potentially small) writes both to stdout and the file. Speed it up with:
{
let mut out = File::new("test.out");
let mut buf = BufWriter::new(out);
let mut lock = io::stdout().lock();
writeln!(lock, "{}", header);
for line in lines {
writeln!(lock, "{}", line);
writeln!(buf, "{}", line);
}
writeln!(lock, "{}", footer);
} // end scope to unlock stdout and flush/close buf>
This locks only once and writes only once the buffer is filled (or buf is closed), so it should be much faster.
Similarly, for network IO, you may want to use buffered IO.