Skip to content

Commit 23b0776

Browse files
authoredJun 26, 2020
Rollup merge of #73529 - pickfire:liballoc-specfromelem-i8, r=cuviper
Add liballoc impl SpecFromElem for i8 Speedup vec![1_i8; N] for non-zero element. Before test do_bench_from_elem_i8 ... bench: 130 ns/iter (+/- 7) = 61 MB/s test do_bench_from_elem_u8 ... bench: 121 ns/iter (+/- 4) = 66 MB/s After test do_bench_from_elem_i8 ... bench: 123 ns/iter (+/- 7) = 65 MB/s test do_bench_from_elem_u8 ... bench: 121 ns/iter (+/- 5) = 66 MB/s No speed difference if element is already zero. ```rust #[bench] fn do_bench_from_elem_i8(b: &mut Bencher) { b.bytes = 8 as u64; b.iter(|| { let dst = ve::vec![10_i8; 100]; assert_eq!(dst.len(), 100); assert!(dst.iter().all(|x| *x == 10)); }) } ``` As suggested by @cuviper https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/SpecForElem.20for.20other.20integers r? @cuviper CC @joshtriplett Edit: Wow, I just realized both reviewers are Josh.
2 parents f13d09a + f66bcc5 commit 23b0776

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed
 

‎src/liballoc/vec.rs

+15-1
Original file line numberDiff line numberDiff line change
@@ -1801,6 +1801,21 @@ impl<T: Clone> SpecFromElem for T {
18011801
}
18021802
}
18031803

1804+
impl SpecFromElem for i8 {
1805+
#[inline]
1806+
fn from_elem(elem: i8, n: usize) -> Vec<i8> {
1807+
if elem == 0 {
1808+
return Vec { buf: RawVec::with_capacity_zeroed(n), len: n };
1809+
}
1810+
unsafe {
1811+
let mut v = Vec::with_capacity(n);
1812+
ptr::write_bytes(v.as_mut_ptr(), elem as u8, n);
1813+
v.set_len(n);
1814+
v
1815+
}
1816+
}
1817+
}
1818+
18041819
impl SpecFromElem for u8 {
18051820
#[inline]
18061821
fn from_elem(elem: u8, n: usize) -> Vec<u8> {
@@ -1845,7 +1860,6 @@ macro_rules! impl_is_zero {
18451860
};
18461861
}
18471862

1848-
impl_is_zero!(i8, |x| x == 0);
18491863
impl_is_zero!(i16, |x| x == 0);
18501864
impl_is_zero!(i32, |x| x == 0);
18511865
impl_is_zero!(i64, |x| x == 0);

0 commit comments

Comments
 (0)
Please sign in to comment.