Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Faster insert for the index == len case #282

Merged
merged 2 commits into from Jun 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 19 additions & 0 deletions benches/bench.rs
Expand Up @@ -96,6 +96,8 @@ make_benches! {
SmallVec<[u64; VEC_SIZE]> {
bench_push => gen_push(SPILLED_SIZE as _),
bench_push_small => gen_push(VEC_SIZE as _),
bench_insert_push => gen_insert_push(SPILLED_SIZE as _),
bench_insert_push_small => gen_insert_push(VEC_SIZE as _),
bench_insert => gen_insert(SPILLED_SIZE as _),
bench_insert_small => gen_insert(VEC_SIZE as _),
bench_remove => gen_remove(SPILLED_SIZE as _),
Expand All @@ -118,6 +120,8 @@ make_benches! {
Vec<u64> {
bench_push_vec => gen_push(SPILLED_SIZE as _),
bench_push_vec_small => gen_push(VEC_SIZE as _),
bench_insert_push_vec => gen_insert_push(SPILLED_SIZE as _),
bench_insert_push_vec_small => gen_insert_push(VEC_SIZE as _),
bench_insert_vec => gen_insert(SPILLED_SIZE as _),
bench_insert_vec_small => gen_insert(VEC_SIZE as _),
bench_remove_vec => gen_remove(SPILLED_SIZE as _),
Expand Down Expand Up @@ -151,6 +155,21 @@ fn gen_push<V: Vector<u64>>(n: u64, b: &mut Bencher) {
});
}

fn gen_insert_push<V: Vector<u64>>(n: u64, b: &mut Bencher) {
#[inline(never)]
fn insert_push_noinline<V: Vector<u64>>(vec: &mut V, x: u64) {
vec.insert(x as usize, x);
}

b.iter(|| {
let mut vec = V::new();
for x in 0..n {
insert_push_noinline(&mut vec, x);
}
vec
});
}

fn gen_insert<V: Vector<u64>>(n: u64, b: &mut Bencher) {
#[inline(never)]
fn insert_noinline<V: Vector<u64>>(vec: &mut V, p: usize, x: u64) {
Expand Down
13 changes: 9 additions & 4 deletions src/lib.rs
Expand Up @@ -1068,17 +1068,22 @@ impl<A: Array> SmallVec<A> {

/// Insert an element at position `index`, shifting all elements after it to the right.
///
/// Panics if `index` is out of bounds.
/// Panics if `index > len`.
pub fn insert(&mut self, index: usize, element: A::Item) {
self.reserve(1);

unsafe {
let (mut ptr, len_ptr, _) = self.triple_mut();
let len = *len_ptr;
assert!(index <= len);
*len_ptr = len + 1;
ptr = ptr.add(index);
ptr::copy(ptr, ptr.add(1), len - index);
if index < len {
ptr::copy(ptr, ptr.add(1), len - index);
} else if index == len {
// No elements need shifting.
} else {
panic!("index exceeds length");
}
*len_ptr = len + 1;
ptr::write(ptr, element);
}
}
Expand Down