Last active
December 13, 2021 07:20
-
-
Save green-s/fbd0d374b290781ac9b3f8ff03e3245d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![feature(test)] | |
extern crate test; | |
extern crate itertools; | |
use test::Bencher; | |
use itertools::Itertools; | |
fn strings_vec() -> Vec<String> { | |
vec![String::from("again"); 512] | |
} | |
#[bench] | |
fn consume_collect_join(b: &mut Bencher) { | |
b.iter(|| { | |
strings_vec() | |
.into_iter() | |
.collect::<Vec<String>>() | |
.join(" and ") | |
}); | |
} | |
#[bench] | |
fn consume_itertools_join(b: &mut Bencher) { | |
b.iter(|| strings_vec().into_iter().join(" and ")); | |
} | |
#[bench] | |
fn borrow_collect_join(b: &mut Bencher) { | |
let strings = strings_vec(); | |
b.iter(|| { | |
strings | |
.iter() | |
.map(|s| &**s) | |
.collect::<Vec<&str>>() | |
.join(" and ") | |
}); | |
} | |
#[bench] | |
fn borrow_itertools_join(b: &mut Bencher) { | |
let strings = strings_vec(); | |
b.iter(|| strings.iter().join(" and ")); | |
} | |
// Results: | |
// | |
// test borrow_collect_join ... bench: 24,071 ns/iter (+/- 11,873) | |
// test borrow_itertools_join ... bench: 41,002 ns/iter (+/- 6,126) | |
// test consume_collect_join ... bench: 63,260 ns/iter (+/- 18,295) | |
// test consume_itertools_join ... bench: 82,640 ns/iter (+/- 30,842) |
perf
shows the consume benches calls malloc
heavily whereas the borrow cases don't. Probable itertools
explanation in rust-itertools/itertools#577 . I don't have a reference for the core lib case.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you'd like to bench it yourself:
Paste gist content to
src/lib.rs
Use nigthly to bench it:
rustup override set nightly cargo bench
My results on Rust nightly 1.39
Conclusion
Use
collect
+join
: faster and no dependencies.