Skip to content

Commit 5059dfe

Browse files
authored
Auto merge of #37094 - fhartwig:spec-extend-from-slice, r=alexcrichton
Specialize Vec::extend to Vec::extend_from_slice I tried using the existing `SpecExtend` as a helper trait for this, but the instances would always conflict with the instances higher up in the file, so I created a new helper trait. Benchmarking `extend` vs `extend_from_slice` with an slice of 1000 `u64`s gives the following results: ``` before: running 2 tests test tests::bench_extend_from_slice ... bench: 166 ns/iter (+/- 78) test tests::bench_extend_trait ... bench: 1,187 ns/iter (+/- 697) after: running 2 tests test tests::bench_extend_from_slice ... bench: 149 ns/iter (+/- 87) test tests::bench_extend_trait ... bench: 138 ns/iter (+/- 70) ```
2 parents d34318d + 63ee8d0 commit 5059dfe

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

src/libcollections/vec.rs

+18-1
Original file line numberDiff line numberDiff line change
@@ -1571,7 +1571,24 @@ impl<T> Vec<T> {
15711571
#[stable(feature = "extend_ref", since = "1.2.0")]
15721572
impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
15731573
fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1574-
self.extend(iter.into_iter().cloned());
1574+
<I as SpecExtendVec<T>>::extend_vec(iter, self);
1575+
}
1576+
}
1577+
1578+
// helper trait for specialization of Vec's Extend impl
1579+
trait SpecExtendVec<T> {
1580+
fn extend_vec(self, vec: &mut Vec<T>);
1581+
}
1582+
1583+
impl <'a, T: 'a + Copy, I: IntoIterator<Item=&'a T>> SpecExtendVec<T> for I {
1584+
default fn extend_vec(self, vec: &mut Vec<T>) {
1585+
vec.extend(self.into_iter().cloned());
1586+
}
1587+
}
1588+
1589+
impl<'a, T: Copy> SpecExtendVec<T> for &'a [T] {
1590+
fn extend_vec(self, vec: &mut Vec<T>) {
1591+
vec.extend_from_slice(self);
15751592
}
15761593
}
15771594

0 commit comments

Comments
 (0)