Skip to content

Feature Request: Shrink capacity of StableGraph to reclaim memory #772

@ekkaiaaa

Description

@ekkaiaaa

Hi there,

I'm using petgraph::stable_graph::StableGraph in a Rust project to represent a directed acyclic graph. Over time, I regularly remove large batches of nodes. However, I've noticed that even after all nodes are removed, the internal capacity of the graph remains high, leading to inefficient memory usage.

For example:

use petgraph::stable_graph::StableGraph;

fn main() {
    let mut graph = StableGraph::<u32, ()>::new();
    let mut nodes = vec![];

    for i in 0..1000 {
        let node = graph.add_node(i);
        nodes.push(node);
    }

    for i in 0..1000 {
        graph.remove_node(nodes[i]);
    }

    println!(
        "Graph capacity is {:?} while its actual node count is {}",
        graph.capacity().0,
        graph.node_count()
    );
}
Graph capacity is 1024 while its actual node count is 0

This suggests that the internal storage is not being shrunk even after all nodes are removed. I understand that StableGraph is designed for stable node indices (and I need this property), which might complicate shrinking, but I'm wondering:

  • Is there a mechanism to reclaim unused capacity/memory in StableGraph?
  • If not, would it be possible to add something like the Graph.shrink_to_fit() method?
  • Alternatively, is recreating a fresh StableGraph the recommended way to reclaim memory, even if it may be expensive?

Metadata

Metadata

Assignees

Labels

A-crateArea: Petgraph crate functionalityC-feature-requestCategory: A feature requestC-performanceCategory: A change motivated by improving speed, memory usage or compile times

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions