为什么read_line(..)比lines()慢得多? [英] Why is read_line(..) much slower than lines()?
问题描述
下面的代码在调用 read_line(..)
而不是行()
时运行得慢得多你无法在操场上运行它,但对我来说这会输出以下内容
The code below runs much slower when calling read_line(..)
than lines()
You can't run it in the playground but for me this prints the following
lines() took Duration { secs: 0, nanos: 41660031 }
read_line() took Duration { secs: 2, nanos: 379397138 }
<的实施code>行 几乎就是我写的(但更多!)为什么会出现这样的差异?
The implementation of Lines
does pretty much what I wrote (but more!) why is there such a difference?
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);
}
推荐答案
让我们来看看你的程序输出:
Let's take a look at the output of your program:
1
2
...
999
1000
1
1
2
1
2
3
1
2
3
4
1
2
3
4
5
...
哎呀。这只是代码中的一个简单错误:你永远不会 clear()
字符串。每个 read_line()
调用都附加到您的字符串。当我在中添加
循环时,时间更具可比性: s.clear()
而
Ooops. It's just a simple bug in your code: you never clear()
the string. Each read_line()
call appends to your string. When I add a s.clear()
in your while
loop, the timings are more comparable:
lines() took Duration { secs: 0, nanos: 7323617 }
read_line() took Duration { secs: 0, nanos: 2877078 }
在您的越野车计划中,大部分时间可能都是浪费重新分配字符串并将其打印到终端。
In your buggy program, most of the time was probably wasted reallocating the string and printing it to the terminal.
这篇关于为什么read_line(..)比lines()慢得多?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!