Skip to content

Instantly share code, notes, and snippets.

@arifd
Created October 20, 2023 21:49
Show Gist options
  • Save arifd/ca648f007e5402c2d7f86f4b857b7c4b to your computer and use it in GitHub Desktop.
Save arifd/ca648f007e5402c2d7f86f4b857b7c4b to your computer and use it in GitHub Desktop.
bench iter flatten collect vs concat
use criterion::{black_box, criterion_group, criterion_main, Criterion};
pub fn concat(v: Vec<Vec<u32>>) -> Vec<u32> {
v.concat()
}
pub fn iter_flatten_collect(v: Vec<Vec<u32>>) -> Vec<u32> {
v.into_iter().flatten().collect()
}
pub fn map_nested_flatten_collect() -> Vec<u32> {
(0..1000).map(|i| vec![i; 1000]).flatten().collect()
}
pub fn map_nested_concat() -> Vec<u32> {
let v = (0..1000).map(|i| vec![i; 1000]).collect::<Vec<_>>();
v.concat()
}
pub fn extend_flatten(v: Vec<Vec<u32>>) -> Vec<u32> {
let mut result = Vec::with_capacity(1000 * 1000);
result.extend(v.into_iter().flatten());
result
}
fn benchmark_concat_vs_flatten_collect(c: &mut Criterion) {
let v: Vec<Vec<u32>> = vec![vec![1; 1000]; 1000];
c.bench_function("concat", |b| b.iter(|| black_box(concat(v.clone()))));
c.bench_function("flatten_collect", |b| {
b.iter(|| black_box(iter_flatten_collect(v.clone())))
});
c.bench_function("nested_flatten_collect", |b| {
b.iter(|| black_box(map_nested_flatten_collect()))
});
c.bench_function("nested_concat", |b| {
b.iter(|| black_box(map_nested_concat()))
});
c.bench_function("extend_flatten", |b| {
b.iter(|| black_box(extend_flatten(v.clone())))
});
}
criterion_group!(benches, benchmark_concat_vs_flatten_collect);
criterion_main!(benches);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment