Skip to content

Read::bytes() is a performance trap #28073

Closed
@eefriedman

Description

@eefriedman
use std::fs::File;
use std::io::Read;
use std::io::BufReader;
fn main() {
    let f = File::open("/usr/share/dict/words").unwrap();
    let f = BufReader::new(f);
    let mut count = 0;
    for b in f.bytes() {
        if b.ok() == Some(b'a') { count += 1 }
    }
    println!("{}", count);
}

On my computer, this takes about 0.011s to run. If you comment out the line to create the BufReader, the code still compiles... but it takes roughly 0m0.209s to run.

It seems like Rust should try to prevent people from shooting themselves in the foot, although I'm not exactly sure what could be done short of deprecating it.

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