From 90d8a1260de0eeb96fd32e13c97b3c8ffd7a4d06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9rome=20Eertmans?= Date: Mon, 12 Feb 2024 11:50:49 +0100 Subject: [PATCH] chore(lib): niche optimizations (#45) --- src/rt/graph.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/rt/graph.rs b/src/rt/graph.rs index 4ec1630d..7b8d8965 100644 --- a/src/rt/graph.rs +++ b/src/rt/graph.rs @@ -30,6 +30,7 @@ pub trait PathsIterator: Iterator> { /// If not all paths have the same depth. /// /// If it cannot allocate enough memory. + #[inline] fn collect_array(&mut self) -> Array2 { let mut flat_vec = Vec::new(); let mut num_paths = 0; @@ -71,6 +72,7 @@ pub mod complete { #[pymethods] impl CompleteGraph { #[new] + #[inline] pub fn new(num_nodes: usize) -> CompleteGraph { Self { num_nodes } } @@ -96,6 +98,7 @@ pub mod directed { self.edges_list[node].as_ref() } + #[inline] pub fn from_adjacency_matrix(adjacency_matrix: &ArrayView2) -> Self { debug_assert!( adjacency_matrix.is_square(), @@ -302,6 +305,7 @@ pub mod directed { } impl From for DiGraph { + #[inline] fn from(graph: CompleteGraph) -> Self { let num_nodes = graph.num_nodes; let mut matrix = Array2::from_elem((num_nodes, num_nodes), true); @@ -335,8 +339,10 @@ pub mod directed { depth: usize, include_from_and_to: bool, ) -> Self { - let stack = vec![graph.get_adjacent_nodes(from).to_vec().into()]; - let visited = vec![from]; + let mut stack = Vec::with_capacity(depth); + let mut visited = Vec::with_capacity(depth); + stack.push(graph.get_adjacent_nodes(from).to_vec().into()); + visited.push(from); Self { graph, @@ -352,6 +358,7 @@ pub mod directed { impl Iterator for AllPathsFromDiGraphIter { type Item = Vec; + #[inline] fn next(&mut self) -> Option { // The current implementation was derived from // the `all_simple_path` function from @@ -397,6 +404,7 @@ pub mod directed { } impl PathsIterator for AllPathsFromDiGraphIter { + #[inline] fn depth(&self) -> Option { if self.include_from_and_to { Some(self.depth) @@ -432,10 +440,12 @@ pub mod directed { impl Iterator for AllPathsFromDiGraphChunksIter { type Item = Array2; + #[inline] fn next(&mut self) -> Option { self.iter.next().map(|mut path| { let mut num_paths = 1; let depth = path.len(); + path.reserve_exact((self.chunk_size - 1) * depth); for _ in 1..(self.chunk_size) { match self.iter.next() { Some(other_path) => {