From 55d0f2e340f73eb2bd8cc35f513133d5774f3a51 Mon Sep 17 00:00:00 2001 From: ljedrz Date: Thu, 22 Oct 2020 12:09:30 +0200 Subject: [PATCH] perf: reduce allocations in the Neg impl for Vec Signed-off-by: ljedrz --- gadgets/src/arithmetic/neg.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/gadgets/src/arithmetic/neg.rs b/gadgets/src/arithmetic/neg.rs index ba199c8eda..a35f474f46 100644 --- a/gadgets/src/arithmetic/neg.rs +++ b/gadgets/src/arithmetic/neg.rs @@ -22,6 +22,8 @@ use snarkos_models::{ gadgets::{r1cs::ConstraintSystem, utilities::boolean::Boolean}, }; +use std::iter; + /// Returns a negated representation of `self` in the constraint system. pub trait Neg where @@ -40,8 +42,9 @@ impl Neg for Vec { let flipped: Self = self.iter().map(|bit| bit.not()).collect(); // add one - let mut one = vec![Boolean::constant(true)]; - one.append(&mut vec![Boolean::Constant(false); self.len() - 1]); + let mut one = Vec::with_capacity(self.len()); + one.push(Boolean::constant(true)); + one.extend(iter::repeat(Boolean::Constant(false)).take(self.len() - 1)); let mut bits = flipped.add_bits(cs.ns(|| "add one"), &one)?; let _carry = bits.pop(); // we already accounted for overflow above