From 0e6e15d201f61e89cc71d4932b924c02a074f278 Mon Sep 17 00:00:00 2001 From: lluni Date: Sun, 5 Feb 2023 18:58:20 +0100 Subject: [PATCH] Allocate vectors with capacity for faster init --- examples/example_sine.rs | 8 ++++---- src/lib.rs | 3 +-- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/examples/example_sine.rs b/examples/example_sine.rs index 87ef3d7..516580f 100644 --- a/examples/example_sine.rs +++ b/examples/example_sine.rs @@ -21,8 +21,8 @@ fn main() { Uniform::new(training_interval.0, training_interval.1), ) .to_vec(); - let mut x_train = Vec::new(); - let mut y_train = Vec::new(); + let mut x_train = Vec::with_capacity(steps); + let mut y_train = Vec::with_capacity(steps); for x in training_values { x_train.push(Array1::from_elem(1usize, x)); y_train.push(Array1::from_elem(1usize, x.sin())); @@ -32,8 +32,8 @@ fn main() { let interval_length = training_interval.1 - training_interval.0; let step_size = interval_length / test_steps as f64; let testing_values = Array1::range(training_interval.0, training_interval.1, step_size); - let mut x_test = Vec::new(); - let mut y_test_true = Vec::new(); + let mut x_test = Vec::with_capacity(test_steps); + let mut y_test_true = Vec::with_capacity(test_steps); for x in testing_values { x_test.push(Array1::from_elem(1usize, x)); y_test_true.push(Array1::from_elem(1usize, x.sin())); diff --git a/src/lib.rs b/src/lib.rs index 2b3f2af..440b317 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -26,8 +26,7 @@ impl Network { } pub fn predict(&mut self, inputs: &[Array1]) -> Vec> { - assert!(!inputs.is_empty()); - let mut result = vec![]; + let mut result = Vec::with_capacity(inputs.len()); for input in inputs.iter() { let mut output = input.to_owned();