为什么read_line(..)比lines()慢得多?

时间:2017-07-20 16:32:00

标签: io rust

调用read_line(..)时,下面的代码运行速度比lines()慢得多 你无法在操场上运行它,但对我来说这会打印以下内容

lines()     took Duration { secs: 0, nanos: 41660031 }
read_line() took Duration { secs: 2, nanos: 379397138 }

implementation of Lines几乎与我所写的相同(但更多!)为什么会出现这样的差异?

use std::net::{TcpListener, TcpStream};
use std::io::{BufRead, BufReader, Write};
use std::thread;

fn main() {

    let listener = TcpListener::bind("127.0.0.1:80")
        .expect("listen failed");
    thread::spawn(move || {
        for stream in listener.incoming() {
            let mut stream = stream.unwrap();
            thread::spawn(move || {
                for x in 1..1000 + 1 {
                    stream.write_all(format!("{}\n", x).as_bytes())
                        .expect("write failed");
                }
            });
        }
    });

    let start_a = std::time::Instant::now();
    {
        let stream_a = TcpStream::connect("127.0.0.1:80")
            .expect("connect_a failed");
        let br = BufReader::new(stream_a);
        for l in br.lines() {
            println!("{}", l.unwrap());
        }
    }
    let end_a = std::time::Instant::now();

    let start_b = std::time::Instant::now();
    {
        let stream_b = TcpStream::connect("127.0.0.1:80")
            .expect("connect_b failed");
        let mut br = BufReader::new(stream_b);
        let mut s = String::with_capacity(10);
        while br.read_line(&mut s).unwrap_or(0) > 0 {
            println!("{}", s);
        }
    }
    let end_b = std::time::Instant::now();

    let dur_a = end_a - start_a;
    let dur_b = end_b - start_b;

    println!("lines()     took {:?}", dur_a);
    println!("read_line() took {:?}", dur_b);

}

same code on the playground

1 个答案:

答案 0 :(得分:9)

让我们来看一下你的程序输出:

1 
2 
...
999
1000
1

1
2

1
2
3

1
2
3
4

1
2
3
4
5

...

糟糕!它只是代码中的一个简单错误:你永远不会clear()字符串。每个read_line()调用都附加到您的字符串。当我在s.clear()循环中添加while时,时间更具可比性:

lines()     took Duration { secs: 0, nanos: 7323617 }
read_line() took Duration { secs: 0, nanos: 2877078 }

在你的越野车计划中,大部分时间都可能浪费了重新分配字符串并将其打印到终端。