Rust IO 在 --release 模式下非常快,但写入时间非常慢

Rust IO when in --release mode incrediably fast, but writing time is horriably slow

如果我需要提供更多信息,请告诉我。所以,我的程序可以立即吃掉一个 75 gig 的 .bin 文件,但是写入这些文件需要很长时间,我想知道是否因为即使它们是 .bin 文件,我仍然可以将它们作为文本读取。这是我写入磁盘的代码:

println!("\nWriting to Disk...\n");
fs::create_dir(Path::new(&name_path)).unwrap();
let mut layer_path = format!("quirkscape/saves/{}/world.bin", name.trim());
let mut world_file = File::create(layer_path).expect("Uh Oh");
for k in data {
    write!(world_file, "{}", k).unwrap();
}

您可以使用 BufWriter 以便分批完成任何写入。

It can be excessively inefficient to work directly with something that implements Write. For example, every call to write on TcpStream results in a system call. A BufWriter<W> keeps an in-memory buffer of data and writes it to an underlying writer in large, infrequent batches.

let mut world_file = BufWriter::new(File::create(layer_path).expect("Uh Oh"));
            
for k in data {
    write!(world_file, "{}", k).unwrap();
}