Skip to content

Inefficient write! macro with vector #46872

@DawidPi

Description

@DawidPi

write! macro, that uses vector to write it's elements into a file is inefficient, as it make write() system call for each letter stored in vector of chars. It could be implemented in a way, that only one write system call is made with all the data, that is to be written.

source code, that shows the issue can be seen with following source code:

extern crate rand;

use rand::Rng;
use std::io::Write;
use std::fs::OpenOptions;

fn generate_character() -> char {
    rand::thread_rng().gen_ascii_chars().next().expect("Could not get character")
}

fn main() {
    let mut vector = Vec::new();

    for _ in 0..10000{
        vector.push(generate_character());
    }

    let mut file = OpenOptions::new().create(true).write(true).open("testfile.txt").unwrap();

    write!(file, "{:?}", vector).expect("Could not write to file");
    file.sync_all().expect("Could not sync all");

    let string : String = vector.iter().collect();
    file.write_all(string.as_bytes()).expect("Could not sync all");
    file.sync_all().expect("Could not sync all");

}

(there is a wrong error log if writing fails but it's not important)

when progam is run with strace we can see, that write! under the hood issues many many system calls, while write_all method uses just one system call. One system call is often more efficient and in some cases even much more efficient.

Attaching logs from the strace and sample project with given source code.

Is there a possibility to fix this issue? I am no Rust expert at all and with macros I know very little, but this certainly is an issue. I see this a some major flaw

strace.log
inefficient write macro.zip

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions