Skip to content

Optimizing Dijkstra: reducing dict lookups (up to 10% faster) - #8191

Closed
amcandio wants to merge 2 commits into
networkx:mainfrom
amcandio:dijkstra_dict_optimization
Closed

amcandio wants to merge 2 commits into
networkx:mainfrom
amcandio:dijkstra_dict_optimization

Conversation

@amcandio

@amcandio amcandio commented Aug 11, 2025 •

Copy link
Copy Markdown
Contributor

Optimize single_source_dijkstra_path_length by reducing redundant dictionary lookups

Summary

This PR refactors Dijkstra loops to avoid redundant dictionary lookups when checking distances and visited nodes.
Instead of accessing dist[u] or seen[u] multiple times it stores the result of dict.get() in a local variable and reuses it.

This potentially saves hash computations and equality checks, especially when:

  • Nodes are strings: Python caches string hashes, so hashing is cheap, but equality checks on long strings are avoided.
  • Nodes are objects with custom, uncached hashes: both hash computation and equality checks can be expensive, so avoiding duplicate lookups saves time.
  • Nodes are integers: hashes are trivial, so gains are minimal here.

Benchmark Results

Benchmarks were run using the suite from #8059, both with integer nodes and with artificially long string node labels. Benchmark was extended to call nx.single_source_dijkstra_path_length and to test with long strings following transformation was used:

self.G = nx.relabel_nodes(self.G, {x: f"{'node-prefix_' * 10}{x}" for x in self.G})

Even though Ratio is higher than 1 in some benchmarks, there is no conclusive increase after looking at variability of measurements.

Integer Nodes

Performance is essentially unchanged or slightly improved (within noise), as expected for cheap hashes and equality checks.

Change Before [a25405f] After [8a2cb3a] Ratio Benchmark (Parameter)
127±0.3μs 124±0.3μs 0.98 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('dijkstra_relaxation_worst_case(100)')
1.50±0.01ms 1.50±0.01ms 1.00 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('dijkstra_relaxation_worst_case(1000)')
17.9±0.04ms 17.7±0.08ms 0.99 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('dijkstra_relaxation_worst_case(10000)')
40.2±0.2ms 39.0±0.7ms 0.97 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('dijkstra_relaxation_worst_case(20000)')
5.60±0.1μs 5.40±0.01μs 0.96 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('weighted_graph(42, gnp_random_graph, 10, 0.1, seed=42)')
10.2±0.08μs 9.82±0.02μs 0.96 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('weighted_graph(42, gnp_random_graph, 10, 0.5, seed=42)')
15.9±0.02μs 15.0±0.03μs 0.94 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('weighted_graph(42, gnp_random_graph, 10, 0.9, seed=42)')
184±0.3μs 175±0.3μs 0.95 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('weighted_graph(42, gnp_random_graph, 100, 0.1, seed=42)')
683±6μs 677±40μs 0.99 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('weighted_graph(42, gnp_random_graph, 100, 0.5, seed=42)')
1.16±0ms 1.08±0ms 0.94 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('weighted_graph(42, gnp_random_graph, 100, 0.9, seed=42)')
19.6±2ms 15.2±0.08ms ~0.77 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('weighted_graph(42, gnp_random_graph, 1000, 0.1, seed=42)')
110±4ms 105±5ms 0.95 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('weighted_graph(42, gnp_random_graph, 1000, 0.5, seed=42)')
215±10ms 198±3ms 0.92 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('weighted_graph(42, gnp_random_graph, 1000, 0.9, seed=42)')
44.6±0.2μs 43.8±0.1μs 0.98 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('weighted_graph(42, path_graph, 100)')
430±10μs 436±3μs 1.01 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('weighted_graph(42, path_graph, 1000)')
4.26±0.07ms 4.16±0.04ms 0.98 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('weighted_graph(42, path_graph, 10000)')
8.56±0.1ms 8.41±0.07ms 0.98 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('weighted_graph(42, path_graph, 20000)')

Long String Nodes

When node labels are long strings, hashing is still cached, but avoiding duplicate lookups saves equality comparisons. This leads to more noticeable improvements.

Change Before [a25405f] After [8a2cb3a] Ratio Benchmark (Parameter)
132±1μs 128±0.7μs 0.97 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('dijkstra_relaxation_worst_case(100)')
1.61±0.01ms 1.53±0ms 0.95 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('dijkstra_relaxation_worst_case(1000)')
19.1±0.09ms 18.5±0.05ms 0.97 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('dijkstra_relaxation_worst_case(10000)')
41.1±2ms 39.6±0.2ms 0.96 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('dijkstra_relaxation_worst_case(20000)')
5.52±0.04μs 5.37±0.06μs 0.97 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('weighted_graph(42, gnp_random_graph, 10, 0.1, seed=42)')
10.7±0.05μs 9.90±0.08μs 0.93 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('weighted_graph(42, gnp_random_graph, 10, 0.5, seed=42)')
- 16.7±0.4μs 15.2±0.02μs 0.91 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('weighted_graph(42, gnp_random_graph, 10, 0.9, seed=42)')
202±6μs 184±0.5μs 0.91 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('weighted_graph(42, gnp_random_graph, 100, 0.1, seed=42)')
759±30μs 694±20μs 0.92 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('weighted_graph(42, gnp_random_graph, 100, 0.5, seed=42)')
- 1.29±0.07ms 1.14±0ms 0.89 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('weighted_graph(42, gnp_random_graph, 100, 0.9, seed=42)')
18.2±0.4ms 17.8±0.4ms 0.98 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('weighted_graph(42, gnp_random_graph, 1000, 0.1, seed=42)')
111±4ms 107±2ms 0.96 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('weighted_graph(42, gnp_random_graph, 1000, 0.5, seed=42)')
227±5ms 244±20ms 1.08 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('weighted_graph(42, gnp_random_graph, 1000, 0.9, seed=42)')
49.8±0.6μs 46.6±0.6μs 0.93 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('weighted_graph(42, path_graph, 100)')
490±3μs 447±2μs 0.91 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('weighted_graph(42, path_graph, 1000)')
5.08±0.07ms 4.72±0.08ms 0.93 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('weighted_graph(42, path_graph, 10000)')
10.3±0.05ms 9.49±0.07ms 0.92 benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra_length('weighted_graph(42, path_graph, 20000)')

@rossbar rossbar 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.

I don't think the performance angle is particularly motivating; to me the changes are in the noise and worrying about the special cases where folks have long/complicated node labels doesn't strike me as particularly motivating either.

That said, the changes themselves seem like nice readability improvements! Replacing x in dict with the walrus operator and dict.get is a nice pattern for reusing results that were already computed. Other things like collapsing the nested if s is also nice. I have one question about the changed condition at the top of the loop but other than that I'm in favor of the changes. Thanks @amcandio !

@amcandio

Copy link
Copy Markdown
Contributor Author

I don't think the performance angle is particularly motivating; to me the changes are in the noise and worrying about the special cases where folks have long/complicated node labels doesn't strike me as particularly motivating either.

That said, the changes themselves seem like nice readability improvements! Replacing x in dict with the walrus operator and dict.get is a nice pattern for reusing results that were already computed. Other things like collapsing the nested if s is also nice. I have one question about the changed condition at the top of the loop but other than that I'm in favor of the changes. Thanks @amcandio !

I can check with smaller strings, I believe I saw an improvement even with smaller ones! Just used big ones to make it more evident.

If there is improvement for smaller strings I would argue it is not just a special case. It's a common pattern to use strings as keys, such as city names

@rossbar rossbar 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.

With the removal of the setdefault bit this LGTM, thanks @amcandio !

@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 have two readability concerns. I am hoping that the speedup here comes from storing v_dist rather than using get instead of in+get_item`. Can you see if the impact of the PR is still about the same with the two suggestions below? Thanks

vu_dist = v_dist + cost
if cutoff is not None and vu_dist > cutoff:
continue
if (u_dist := dist.get(u)) is not None:

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.

This is much harder for me to read. In quick tests, it seems that using get is slightly faster if u in dist, but slower if u not in dist. So the overall timing probably depends on the network structure.
The readable difficulty for me is that we lose the "english language" nature of u in dist, and it relies on the trait that get returns None as the default value. I can't find any way to read that one line and based on what it says (rather than logic beyond what it says) tell what it is doing. Contrast that with if u in dist: u_dist = dist[u].

Suggested change
if (u_dist := dist.get(u)) is not None:
if u in dist:
u_dist = dist[u]

My question is: does this change affect the timing? Or is the savings elsewhere driving the speedup?

# We must store *all* predecessors because `pred` was provided by the caller.
pred[u].append(v)
elif u not in seen or vu_dist < seen[u]:
elif (u_seen := seen.get(u)) is None or vu_dist < u_seen:

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 would prefer the following for readability. It saves the u_seen lookup in the elif below, but restores the english language part of the if-clause (which makes this suggestion very slightly slower than using get(u) when u in seen and very slightly faster when u not in seen)

Suggested change
elif (u_seen := seen.get(u)) is None or vu_dist < u_seen:
elif u not in seen or vu_dist < (u_seen := seen[u]):

Again, the question is whether this particular change affects the timing, or is the savings elsewhere in this PR driving the speedup.

@amcandio

Copy link
Copy Markdown
Contributor Author

I don't think these optimizations are worth pursuing anymore, especially since some of the dict access re-use was already addressed in #8218. So I’ll close this one!

It would be great if we could merge #8059, since it contains all the benchmarks I relied on during the shortest-path optimization work.

@amcandio amcandio closed this Sep 21, 2025
@amcandio
amcandio deleted the dijkstra_dict_optimization branch September 21, 2025 17:25
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.

3 participants