Skip to content

Commit fab7dff

Browse files
authored
Reuse inner allocation in collect_bicolor_runs (#1578)
This commit removes an unecessary iteration of every iteration of the loop inside collect_bicolor_runs(). The vec collection on every iteration of the loop results in a lot of allocations and frees for every node in the graph. We can reuse a single vec between each iteration and avoid this memory pressure.
1 parent 4c2ac5f commit fab7dff

1 file changed

Lines changed: 11 additions & 13 deletions

File tree

rustworkx-core/src/dag_algo.rs

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -588,17 +588,15 @@ where
588588
};
589589
}
590590

591+
let mut colors = Vec::new();
591592
for node in nodes {
592593
if let Some(is_match) = filter_fn(node)? {
594+
colors.clear();
593595
let raw_edges = graph.edges_directed(node, petgraph::Direction::Outgoing);
594596

595-
// Remove all edges that yield errors from color_fn
596-
let colors = raw_edges
597-
.map(|edge| color_fn(edge.id()))
598-
.collect::<Result<Vec<Option<usize>>, _>>()?;
599-
600-
// Remove null edges from color_fn
601-
let colors = colors.into_iter().flatten().collect::<Vec<usize>>();
597+
for color in raw_edges.filter_map(|edge| color_fn(edge.id()).transpose()) {
598+
colors.push(color?);
599+
}
602600

603601
match (colors.len(), is_match) {
604602
(1, true) => {
@@ -638,13 +636,13 @@ where
638636
}
639637
}
640638
_ => {
641-
for color in colors {
642-
ensure_vector_has_index!(pending_list, block_id, color);
643-
if let Some(color_block_id) = block_id[color] {
644-
block_list[color_block_id].append(&mut pending_list[color]);
639+
for color in &colors {
640+
ensure_vector_has_index!(pending_list, block_id, *color);
641+
if let Some(color_block_id) = block_id[*color] {
642+
block_list[color_block_id].append(&mut pending_list[*color]);
645643
}
646-
block_id[color] = None;
647-
pending_list[color].clear();
644+
block_id[*color] = None;
645+
pending_list[*color].clear();
648646
}
649647
}
650648
}

0 commit comments

Comments
 (0)