Skip to content

State-of-the-art implementation of Tarjan's algorithm - #8615

Merged
dschult merged 2 commits into
networkx:mainfrom
vigna:tarjan
Apr 16, 2026
Merged

dschult merged 2 commits into
networkx:mainfrom
vigna:tarjan

Conversation

@vigna

@vigna vigna commented Apr 13, 2026 •

Copy link
Copy Markdown
Contributor

The current implementation of the computation of strongs components in NetworkX is the same as that of SciPy: it is a two-pass algorithm that needlessly scan every arc twice and allocates significantly more memory than necessary.

The SciPy version will be replaced in 1.18 with a state-of-the art implementation of Tarjan's algorithm that I coded starting from Tarjan and Zwick's recent survey (see the SciPy PR for details).

This PR implements essentially the same algorithm for NetworkX. The same comments apply: the algorithm is more than twice faster because, beside halving the visit time, it has better locality. Reduction of memory footprint is more difficult to determine, but it should be better than that of SciPy because this version does not materialize iterators on successors unless they are on the the visit stack.

This simple benchmark gives the following results with the current NetworkX version:

============================================================
Erdős–Rényi  N=100,000  avg_deg=20  nnz=2,000,000  nodes=100,000
  nx.strongly_connected_components : 0.8152s  (1 components)

============================================================
Single SCC   N=100,000  avg_deg≈20  nnz=1,999,808  nodes=100,000
  nx.strongly_connected_components : 0.8201s  (1 components)

============================================================
Chain (DAG)  N=200,000  edges=199999  nnz=199,999  nodes=200,000
  nx.strongly_connected_components : 0.1499s  (200,000 components)

These are the results with the new implementation:

============================================================
Erdős–Rényi  N=100,000  avg_deg=20  nnz=2,000,000  nodes=100,000
  nx.strongly_connected_components : 0.3328s  (1 components)

============================================================
Single SCC   N=100,000  avg_deg≈20  nnz=1,999,808  nodes=100,000
  nx.strongly_connected_components : 0.3373s  (1 components)

============================================================
Chain (DAG)  N=200,000  edges=199999  nnz=199,999  nodes=200,000
  nx.strongly_connected_components : 0.0946s  (200,000 components)

UPDATE: Sorry, I said 30% decrease in space but it's actually data-dependent. The Scipy version uses at most three words per node, with one word coming from the sum of the lengths of the visit and component stacks, which is bounded by the number of nodes.

@vigna

vigna commented Apr 13, 2026

Copy link
Copy Markdown
Contributor Author

I should add that the code looks quite different because the SciPy version just leaves a component index in an array, whereas NetworkX's version is a generator returning components as they are identified by the algorithm.

scc_found.update(scc)
if source in lowlink:
continue
index += 1

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to track index if we do lowlink[source] = len(lowlink) + 1 every time?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Technically, no, but increasing an integer is faster than computing the length of a dictionary (and here I might be wrong—I'm not exactly a Python expert). Moreover, it is closer to the basic algorithm description, which uses arrays rather than dictionaries as nodes are assumed to be integers in [0..n).

lowlink[source] = index
dfs_v.append(source)
dfs_it.append(iter(adj[source]))
dfs_lead.append(True)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have you considered using an integer here?

# push True / False
bits = (bits << 1) | 1   # push True
bits = (bits << 1)       # push False

# peek
top = bits & 1

# set top = False
bits &= ~1

# pop
top = bits & 1
bits >>= 1

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It doesn't seem like a good idea—it's twice as slow:

============================================================
Erdős–Rényi  N=100,000  avg_deg=20  nnz=2,000,000  nodes=100,000
  nx.strongly_connected_components : 0.6233s  (1 components)

============================================================
Single SCC   N=100,000  avg_deg≈20  nnz=1,999,808  nodes=100,000
  nx.strongly_connected_components : 0.6290s  (1 components)

============================================================
Chain (DAG)  N=200,000  edges=199999  nnz=199,999  nodes=200,000
  nx.strongly_connected_components : 1.0897s  (200,000 components)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interesting, thanks for trying it out! It seems like pure python bitsets are not really performat

comp_stack = []
index = 0

for source in G:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could iter adj here:

for source, neighbors in adj.items():
    ...

@vigna vigna Apr 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I cannot find any measurable difference. The form you propose, however, is misleading to the reader who wants to understand the algorithm, because most of the times we will not use the neighbors.

# v is an SCC root: pull its members off comp_stack.
v_low = lowlink[v]
scc = {v}
while comp_stack and lowlink[comp_stack[-1]] >= v_low:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could remove this dict access by storing (v, lowlink[v]) in th comp_stack but not 100% sure it will necessarily be faster.

@amcandio

amcandio commented Apr 14, 2026 •

Copy link
Copy Markdown
Contributor

Very cool, thanks for this! It would be great to run benchmarks in DirectedAlgorithmBenchmarks

@vigna

vigna commented Apr 14, 2026

Copy link
Copy Markdown
Contributor Author

Very cool, thanks for this! It would be great to run benchmarks in DirectedAlgorithmBenchmarks

I'm desperately trying, but if you don't have the full stack conda/pip/whatever up is a bit difficult. Also, the benchmarks (that I was able to run, I believe, in the current version) are incredibly small—the timings are very noisy. The benchmark I posted uses graphs that are two order of magnitude larger.

@vigna

vigna commented Apr 14, 2026

Copy link
Copy Markdown
Contributor Author

Ok, somehow I made it.

Well, this is a bloodbath 😂. I mean, there are measurament that change unit. The complete graph on 1000 nodes is 5x faster.

                          graph
              ------------------------------ -------------
                 Erdos Renyi (100, 0.005)      55.9±0.8μs
                 Erdos Renyi (100, 0.01)       63.8±0.4μs
                 Erdos Renyi (100, 0.05)        140±2μs
                  Erdos Renyi (100, 0.1)        228±1μs
                  Erdos Renyi (100, 0.5)        873±7μs
                Erdos Renyi (1000, 0.0005)      587±10μs
                Erdos Renyi (1000, 0.001)       698±5μs
                Erdos Renyi (1000, 0.005)     1.66±0.06ms
                 Erdos Renyi (1000, 0.01)     2.43±0.04ms
                 Erdos Renyi (1000, 0.05)      9.15±0.2ms
               Erdos Renyi (10000, 0.00005)    7.19±0.2ms
               Erdos Renyi (10000, 0.0001)     8.34±0.6ms
               Erdos Renyi (10000, 0.0005)     18.1±0.6ms
                       Empty (100)             47.8±0.2μs
                       Empty (1000)             472±8μs
                      Empty (10000)            5.06±0.1ms
                      Complete (100)          1.63±0.01ms
                     Complete (1000)           160±0.4ms
              ============================== =============

New:

                            graph
                ------------------------------ -------------
                   Erdos Renyi (100, 0.005)      43.5±10μs
                   Erdos Renyi (100, 0.01)       48.0±0.2μs
                   Erdos Renyi (100, 0.05)       54.3±0.4μs
                    Erdos Renyi (100, 0.1)       64.3±0.5μs
                    Erdos Renyi (100, 0.5)        159±2μs
                  Erdos Renyi (1000, 0.0005)      436±5μs
                  Erdos Renyi (1000, 0.001)       507±8μs
                  Erdos Renyi (1000, 0.005)       890±10μs
                   Erdos Renyi (1000, 0.01)       981±6μs
                   Erdos Renyi (1000, 0.05)     1.81±0.01ms
                 Erdos Renyi (10000, 0.00005)    4.97±0.2ms
                 Erdos Renyi (10000, 0.0001)     5.84±0.6ms
                 Erdos Renyi (10000, 0.0005)     10.8±0.6ms
                         Empty (100)             38.2±0.3μs
                         Empty (1000)             370±3μs
                        Empty (10000)           3.91±0.04ms
                        Complete (100)            283±4μs
                       Complete (1000)          27.2±0.08ms
                ============================== =============

@amcandio amcandio left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Amazing, I was not aware of this state of the art implementation. I approve this PR. Thank you so much!

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very nice!
It works better -- not crushingly, but systematically.
Go Tarjan! :)

I am surprised that a single queue of 3-tuples is slower than 3 separate queues. And even a queue 2-tuples and a set to hold any nodes where lead is False is slower. We may have to pay attention to our other queues -- many of them store tuples in the stack. Part of what may make this slower is the update that has to pass over the remaining stack members just to pull off the first entry in the tuple. But I'm not sure. rapping and unwrapping tuples may be part of the relatively high cost of calling functions in Python too. fun fun with optimizing python!

I have two comments below. One is a doc word issue and the other is a test question.

Comment on lines +179 to +180
assert len(components) == 1
assert components[0] == {0, 1, 2, 3, 4, 5}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this actually test that the code bails? It looks like it is only testing that a single scc is returned... not that the code stopped once it found all the nodes. Thoughts?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test is designed so that the exit is early. I checked with a smoke test (adding a print) that this is actually the case. But there's no way that comes to my mind to embed that in the test.

@vigna

vigna commented Apr 16, 2026

Copy link
Copy Markdown
Contributor Author

Very nice! It works better -- not crushingly, but systematically. Go Tarjan! :)

Not crushingly? Are we looking at the same benchmarks? 😅

I am surprised that a single queue of 3-tuples is slower than 3 separate queues. And even a queue 2-tuples and a set to hold any nodes where lead is False is slower. We may have to pay attention to our other queues -- many of them store tuples in the stack. Part of what may make this slower is the update that has to pass over the remaining stack members just to pull off the first entry in the tuple. But I'm not sure. rapping and unwrapping tuples may be part of the relatively high cost of calling functions in Python too. fun fun with optimizing python!

So, one thing I discovered checking how things are implemented in Python is that apparently the list of lead bits uses a pointer per Boolean 🥶. So that's not a bit. It is possible to replace the list with a byte array, reducing radically the space but (shockingly) benchmarks are 10% slower. I leave to you the choice.

@dschult

dschult commented Apr 16, 2026

Copy link
Copy Markdown
Member

Not crushingly? Are we looking at the same benchmarks? 😅

hee hee.... I guess it depends on perspective. It's a factor of ~2. That's significant for sure, but I usually reserve crushingly for factors of 10 or 100. :)

I am fine with the handling of the bool dfs_lead here. I would have used a dict/set to store the "False" nodes but it doesn't matter much. Just slightly more readable IMO. That's up to you.

I would like your take on the test that says in comments that it is checking that the code bails early -- but it actualy only tests that the answer is correct -- not that the code bailed. Since we cant really check if bailing has occurred, should we keep this teat?

@vigna

vigna commented Apr 16, 2026

Copy link
Copy Markdown
Contributor Author

hee hee.... I guess it depends on perspective. It's a factor of ~2. That's significant for sure, but I usually reserve crushingly for factors of 10 or 100. :)

Definitely different benchmarks. It's almost 6x faster on the complete graphs in NetworkX benchmarks.

I am fine with the handling of the bool dfs_lead here. I would have used a dict/set to store the "False" nodes but it doesn't matter much. Just slightly more readable IMO. That's up to you.

A dictionary would be much slower—the entire point of the bit stack is locality of access. I'm not suggesting a different data structure, I'm saying that using a bytearray every boolean costs a byte, whereas now it costs a pointer, which is a lot. But it's faster because... because Python 🤷🏻‍♂️.

I would like your take on the test that says in comments that it is checking that the code bails early -- but it actualy only tests that the answer is correct -- not that the code bailed. Since we cant really check if bailing has occurred, should we keep this teat?

I checked and it does. It tests all the partial exit conditions. If someone fiddles with the code and disturbs the invariants it helps, as it could early exit with a wrong component.

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suspect a couple of dictionaries (one for the LIFO queue {v: iter(adj[v])}) and one for the lead tracking) and some len(lowlink) calls could make this simpler, but probably not faster. But I am confident that @vigna has investigated the speed issues here --

It's very nice to include the improved algorithms!
And it is really cool that Tarjan followed up on the 1972 paper with a 2024 paper!!!! Only 52 years later!

I approve this PR. And I give a big thank you to @vigna for providing so much tempting structure here to optimize anything and everything. Rabbit hole alert! :)

@dschult
dschult merged commit 33d7236 into networkx:main Apr 16, 2026
44 checks passed
@dschult dschult added this to the 3.7 milestone Apr 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Development

Successfully merging this pull request may close these issues.

4 participants