Skip to content

Instantly share code, notes, and snippets.

@kirushik
Last active November 13, 2017 17:34
Show Gist options
  • Save kirushik/e0d93759b0cd102f814408595c20a9d0 to your computer and use it in GitHub Desktop.
Save kirushik/e0d93759b0cd102f814408595c20a9d0 to your computer and use it in GitHub Desktop.
#![feature(test)]
extern crate test;
use test::{Bencher, black_box};
use std::iter;
const TOTAL_SIZE: usize = 1024;
const TAIL_DATA: [u8; 24] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24];
#[bench]
fn populate_vec_with_iter(b: &mut Bencher) {
let mut tail_size = 0usize;
b.iter(|| {
let mut buffer = Vec::with_capacity(TOTAL_SIZE);
buffer.extend(iter::repeat(0).take(TOTAL_SIZE - tail_size));
buffer.extend_from_slice(&TAIL_DATA[0..tail_size]);
black_box(buffer);
tail_size = (tail_size + 23) / 19;
});
}
#[bench]
fn populate_vec_with_slice(b: &mut Bencher) {
let mut tail_size = 0usize;
b.iter(|| {
let mut buffer = Vec::with_capacity(TOTAL_SIZE);
buffer.extend_from_slice(&vec![0; TOTAL_SIZE - tail_size]);
buffer.extend_from_slice(&TAIL_DATA[0..tail_size]);
black_box(buffer);
tail_size = (tail_size + 23) / 19;
});
}
#[bench]
fn populate_vec_with_split_at_mut(b: &mut Bencher) {
let mut tail_size = 0usize;
b.iter(|| {
let mut buffer = vec![0; TOTAL_SIZE];
{
let (_head, tail) = buffer.split_at_mut(TOTAL_SIZE - tail_size);
tail.copy_from_slice(&TAIL_DATA[0..tail_size])
}
black_box(buffer);
tail_size = (tail_size + 23) / 19;
});
}
@kirushik
Copy link
Author

     Running target/release/deps/populate_vec-77ce8e8662cf94dc

running 3 tests
test populate_vec_with_iter         ... bench:       1,277 ns/iter (+/- 85)
test populate_vec_with_slice        ... bench:         188 ns/iter (+/- 15)
test populate_vec_with_split_at_mut ... bench:          63 ns/iter (+/- 5)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment