Shave off 2% by optimizing check_partial_products (#205)

* Shave off 2% by optimizing check_partial_products

Removes a bunch of allocations/deallocations

* Minor style (Daniel PR comment)
This commit is contained in:
Jakub Nabaglo 2021-08-28 14:59:56 -07:00 committed by GitHub
parent a71966f6f5
commit 21b263ee3e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -43,19 +43,18 @@ pub fn num_partial_products(n: usize, max_degree: usize) -> (usize, usize) {
/// products of size `max_degree` or less. /// products of size `max_degree` or less.
pub fn check_partial_products<T: Product + Copy + Sub<Output = T>>( pub fn check_partial_products<T: Product + Copy + Sub<Output = T>>(
v: &[T], v: &[T],
partials: &[T], mut partials: &[T],
max_degree: usize, max_degree: usize,
) -> Vec<T> { ) -> Vec<T> {
let mut res = Vec::new(); let mut res = Vec::new();
let mut remainder = v.to_vec(); let mut remainder = v;
let mut partials = partials.to_vec();
while remainder.len() > max_degree { while remainder.len() > max_degree {
let products = remainder let products = remainder
.chunks(max_degree) .chunks(max_degree)
.map(|chunk| chunk.iter().copied().product()) .map(|chunk| chunk.iter().copied().product::<T>());
.collect::<Vec<T>>(); let products_len = products.len();
res.extend(products.iter().zip(&partials).map(|(&a, &b)| a - b)); res.extend(products.zip(partials).map(|(a, &b)| a - b));
remainder = partials.drain(..products.len()).collect(); (remainder, partials) = partials.split_at(products_len);
} }
res res