Skip to content

Optimizing Dijkstra's paths to target (~50x faster for graphs with multiple-hops shortest path) - #8023

Merged
rossbar merged 7 commits into
networkx:mainfrom
amcandio:dijkstras_paths_to_target
Jul 24, 2025
Merged

rossbar merged 7 commits into
networkx:mainfrom
amcandio:dijkstras_paths_to_target

Conversation

@amcandio

@amcandio amcandio commented May 5, 2025 •

Copy link
Copy Markdown
Contributor

Summary

Optimize Dijkstra's algorithm when a single target is specified by avoiding full path reconstruction for all nodes.

Motivation

In the current implementation of _dijkstra_multisource, when the paths argument is provided, paths are computed and stored for all reachable nodes. However, if only a specific target node is of interest, this can be wastefully expensive.

This change avoids storing all paths when only a target is specified, and instead reconstructs the path to the target at the end using the pred dictionary, which is much cheaper to maintain.

Changes

  • Skip path storage during the main loop if only a specific target is requested.
  • Use pred (predecessor map) to reconstruct the path to target at the end.
  • Add a lightweight reconstruction loop to build paths[target] from pred.

Performance

This change reduces memory usage and computation time when:

  • A target is specified.
  • paths is requested.
  • There is no need to compute all paths from the source(s) to every reachable node.

When a specific target node is provided, the original implementation constructs full paths to all reachable nodes using paths[v] + [u] on each edge relaxation. This adds an extra cost of O(n * L), where n is the number of reachable nodes and L is the average path length, due to repeated list copying. By skipping full path construction during the main loop and reconstructing only the path to target at the end , we reduce the path-building cost to just O(L). This optimization is particularly noticeable in graphs where the shortest path to the target has many hops (especially in the worst case where L = n).

Notes

  • The pred dictionary is now always initialized when target and paths are specified (if not already provided), as it's required for final path reconstruction.
  • This change preserves existing behavior and output structure.

No public API changes are introduced.

Results

Optimization adds the most value when the shortest paths to the target has many hops. In the case of the line graph of length 10_000, computing the source from node 0 to node 999 gets ~27x faster.

import networkx as nx
import timeit
 
REPEATS = 100
 
def generate_graphs():
    return {"line_10000": nx.path_graph(10_000)}

def time_dijkstra(G):
    return min(timeit.timeit(lambda: nx.single_source_dijkstra(G, 0, target=len(G)-1), number=1) for _ in range(REPEATS))

for name, G in generate_graphs().items():
    print(f"{name}: min time over {REPEATS} runs = {time_dijkstra(G):.6f} sec")   

Without optimization

line_10000: min time over 100 runs = 0.408241 sec

With optimization

line_10000: min time over 100 runs = 0.014789 sec

Benchmarking results

Run used it asv command with a custom benchmark. Benchmarking for shortest-paths is added in #8059 to not increase the scope of this one too much.

Results showed that performance doesn't significantly change for most graphs in benchmark but significantly improve
s for paths with long shortest path (such as the path graph). In line graphs of 20000 nodes, new implementation is 50 times faster.

(networkx-dev) bash-3.2$ asv compare 092f50e5 a1575792
Couldn't load asv.plugins._mamba_helpers because
No module named 'libmambapy'

All benchmarks:

| Change   | Before [092f50e5]             | After [a1575792]           |   Ratio | Benchmark (Parameter)                                                                                                                        |
|----------|-------------------------------|----------------------------|---------|----------------------------------------------------------------------------------------------------------------------------------------------|
| -        | 124±2μs                       | 107±0.5μs                  |    0.87 | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('dijkstra_relaxation_worst_case(100)')                      |
| -        | 2.50±0.1ms                    | 1.26±0ms                   |    0.5  | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('dijkstra_relaxation_worst_case(1000)')                     |
| -        | 306±8ms                       | 15.0±0.02ms                |    0.05 | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('dijkstra_relaxation_worst_case(10000)')                    |
| -        | 1.19±0.01s                    | 31.6±0.3ms                 |    0.03 | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('dijkstra_relaxation_worst_case(20000)')                    |
|          | 3.51±0.01μs                   | 3.58±0.02μs                |    1.02 | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('weighted_graph(42, gnp_random_graph, 10, 0.1, seed=42)')   |
|          | 8.17±0.1μs                    | 7.94±0.01μs                |    0.97 | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('weighted_graph(42, gnp_random_graph, 10, 0.5, seed=42)')   |
|          | 9.36±0.09μs                   | 8.74±0.01μs                |    0.93 | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('weighted_graph(42, gnp_random_graph, 10, 0.9, seed=42)')   |
|          | 162±0.3μs                     | 156±0.4μs                  |    0.96 | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('weighted_graph(42, gnp_random_graph, 100, 0.1, seed=42)')  |
|          | 574±4μs                       | 549±0.2μs                  |    0.96 | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('weighted_graph(42, gnp_random_graph, 100, 0.5, seed=42)')  |
|          | 546±30μs                      | 503±10μs                   |    0.92 | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('weighted_graph(42, gnp_random_graph, 100, 0.9, seed=42)')  |
|          | 12.0±0.06ms                   | 11.6±0.4ms                 |    0.97 | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('weighted_graph(42, gnp_random_graph, 1000, 0.1, seed=42)') |
|          | 82.4±1ms                      | 83.7±2ms                   |    1.02 | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('weighted_graph(42, gnp_random_graph, 1000, 0.5, seed=42)') |
|          | 53.8±4ms                      | 52.2±3ms                   |    0.97 | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('weighted_graph(42, gnp_random_graph, 1000, 0.9, seed=42)') |
| -        | 58.0±1μs                      | 50.4±0.2μs                 |    0.87 | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('weighted_graph(42, path_graph, 100)')                      |
| -        | 1.22±0.06ms                   | 484±5μs                    |    0.4  | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('weighted_graph(42, path_graph, 1000)')                     |
| -        | 144±8ms                       | 4.91±0.05ms                |    0.03 | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('weighted_graph(42, path_graph, 10000)')                    |
| -        | 527±8ms                       | 9.82±0.04ms                |    0.02 | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('weighted_graph(42, path_graph, 20000)')                    |

@amcandio

amcandio commented May 5, 2025

Copy link
Copy Markdown
Contributor Author

There might be a case where computing all predecessors can be slower than computing the list. Need to experiment more but that could be easily fix by an internal Boolean parameter that limits the amount of predecessors to 1.

@amcandio

amcandio commented May 6, 2025

Copy link
Copy Markdown
Contributor Author

There might be a case where computing all predecessors can be slower than computing the list. Need to experiment more but that could be easily fix by an internal Boolean parameter that limits the amount of predecessors to 1.

I tried with a graph with a bunch of predecessors (~10k) and not really much change:

    N = 10000
    fan = nx.Graph()
    fan.add_node(0)
    fan.add_node(N - 1)
    for mid in range(1, N - 1):
        fan.add_edge(0, mid)
        fan.add_edge(mid, N - 1)
    graphs["fan_two_step_undirected_10000"] = fan

@amcandio amcandio changed the title Optimizing Dijkstra's paths to target (~27x faster for graphs with long diameter) Optimizing Dijkstra's paths to target (~27x faster for graphs with multiple-hops shortest path) May 6, 2025

@fei0319 fei0319 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 think we can push the optimization even further!

This path reconstruction technique can be extended to target is None cases. We can completely deprecate the old way of list copying (paths[u] = paths[v] + [u]), and reconstruct paths for all targets, even when we have more than one target.

The point of doing so is that list copying can happen up to $O(m)$ times (Dijkstra relaxes for at most $O(m)$ times), making the total complexity $O(nm)$. With your optimization, we only need to reconstruct paths for $n$ nodes, each of which is of no more than $n-1$ edges, decreasing the complexity to $O(n^2)$.

This should work well with dense graphs. For sparse graphs, the reconstruction method could be slower than the original one due to cache or something. The following method can be used to speed up (it should be rather efficient):

# Note that the Dijkstra algorithm inserts node to dist in ascending order of distance
for u in dist:
    paths[u] = paths[pred[u][0]] + [u]

So we come back to list copying. The only difference is that we used to copy list upon every relaxation in Dijkstra (for at most $m$ times); now we only do it exactly once for each node (for exactly $n$ times).

Another consideration is that, in the original implementation paths are set for all nodes before target when target is given, while in only paths[target] is set in this one. Additionally, the original implementation searched all the graph without breaking if target is not in G, while the new implementation will set paths[target] to [target]. It seems these issues are handled by the wrapping functions, so it should be fine.

@amcandio

amcandio commented May 6, 2025

Copy link
Copy Markdown
Contributor Author

I think we can push the optimization even further!

This path reconstruction technique can be extended to target is None cases. We can completely deprecate the old way of list copying (paths[u] = paths[v] + [u]), and reconstruct paths for all targets, even when we have more than one target.

The point of doing so is that list copying can happen up to $O(m)$ times (Dijkstra relaxes for at most $O(m)$ times), making the total complexity $O(nm)$. With your optimization, we only need to reconstruct paths for $n$ nodes, each of which is of no more than $n-1$ edges, decreasing the complexity to $O(n^2)$.

This should work well with dense graphs. For sparse graphs, the reconstruction method could be slower than the original one due to cache or something. The following method can be used to speed up (it should be rather efficient):

# Note that the Dijkstra algorithm inserts node to dist in ascending order of distance
for u in dist:
    paths[u] = paths[pred[u][0]] + [u]

So we come back to list copying. The only difference is that we used to copy list upon every relaxation in Dijkstra (for at most $m$ times); now we only do it exactly once for each node (for exactly $n$ times).

Another consideration is that, in the original implementation paths are set for all nodes before target when target is given, while in only paths[target] is set in this one. Additionally, the original implementation searched all the graph without breaking if target is not in G, while the new implementation will set paths[target] to [target]. It seems these issues are handled by the wrapping functions, so it should be fine.

Yes! I struggled a bit building examples where the all-targets case optimization would be noticeable. But I can keep on digging and maybe do it in a separate PR.

# Note that the Dijkstra algorithm inserts node to dist in ascending order of distance
for u in dist:
    paths[u] = paths[pred[u][0]] + [u]

Maybe with this trick it becomes noticeable! This should be faster than doing the N dict lookups

What I had in mind for the all-targets case was returning lazy paths so the construction is only done when needed. It changes the API a bit but we could do it in a way where most users won't notice (as long they don't depend on stuff like type(list)). This should significantly reduce memory consumption as well.

class pathlist(list):
    __slots__ = ('pred', 'start', '_wrapped')

    def __init__(self, pred, start):
        self.pred = pred
        self.start = start
        self._wrapped = None
        super().__init__()

    def _ensure_initialized(self):
        pred = self.pred
        if pres is not None:
            path = []
            current = self.start
            while current is not None:
                path.append(current)
                current = pred.get(current)
            path.reverse()
            self._wrapped = path
            self.pred = None

    def __getitem__(self, index):
        self._ensure_initialized()
        return self._wrapped.__getitem__(index)

    def __iter__(self):
        self._ensure_initialized()
        return self._wrapped.__iter__()

    def __len__(self):
        self._ensure_initialized()
        return self._wrapped.__len__()

    def __repr__(self):
        self._ensure_initialized()
        return self._wrapped.__repr__()

@LorentzFactor

Copy link
Copy Markdown
Contributor

Small suggestion for the sketch of the pathlist class - pred[u] is a list of potentially more than 1 predecessor. So I think it should be current = pred.get(current)[0] instead of current = pred.get(current).

@amcandio

Copy link
Copy Markdown
Contributor Author

Hey @dschult @rossbar do you think you can review this small one? Further improvements require more profiling so I'd prefer to do them in a separate PR

Comment on lines +892 to +898
reversed_target_path = []
next_node = target
while next_node is not None:
reversed_target_path.append(next_node)
next_nodes = pred.get(next_node)
next_node = next_nodes and next_nodes[0]
paths[target] = list(reversed(reversed_target_path))

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.

If you use a deque you can appendleft and avoid having to reverse the list.
I also feel this is cleaner get logic, but you decide.

Suggested change
reversed_target_path = []
next_node = target
while next_node is not None:
reversed_target_path.append(next_node)
next_nodes = pred.get(next_node)
next_node = next_nodes and next_nodes[0]
paths[target] = list(reversed(reversed_target_path))
next_node = target
paths[target] = deque()
while next_node is not None:
paths[target].appendleft(next_node)
next_node = pred.get(next_node, [None])[0]
paths[target] = list(paths[target])

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 re-wrote this. I ended up using arraylist + in-place reversal. I believe this is still clear and should be faster. Did a quick experiment with 10k elements and list+in-place reverse is something like 40% faster. That is like ~2 ms for long lists such as 10k elements, but given that this method is one of the most used algorithms, I believe it's worth it.

n = 10000

def list_append_reverse():
    path = []
    for i in range(n):
        path.append(i)
    path.reverse()
    return path

def deque_appendleft():
    path = deque()
    for i in range(n):
        path.appendleft(i)
    return list(path)

list_append_reverse_time = timeit.timeit(list_append_reverse, number=1000)
deque_appendleft_time = timeit.timeit(deque_appendleft, number=1000)

list_append_reverse_time, deque_appendleft_time

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

The high-level motivation is clear and the code changes are (IMO) relatively minor and straightforward to understand. The next step in my book would be to add some explicit benchmarks to the benchmark suite to help reproducibly probe the impact of the changes!

@amcandio

amcandio commented May 20, 2025 •

Copy link
Copy Markdown
Contributor Author

The high-level motivation is clear and the code changes are (IMO) relatively minor and straightforward to understand. The next step in my book would be to add some explicit benchmarks to the benchmark suite to help reproducibly probe the impact of the changes!

Added benchmark results! I need to clean-up benchmarking code a bit so I will send the benchmarks in a separate PR

@amcandio

amcandio commented May 27, 2025 •

Copy link
Copy Markdown
Contributor Author

@dschult @rossbar do you think there’s more work needed here?

I sent a follow-up PR to add benchmarks: #8059. In cases where the shortest path has few hops, the new version performs similarly to the old one, which makes sense, since Dijkstra already doesn’t need to explore much of the graph in those cases.

The improvement really shines in harder cases, where Dijkstra has to explore many nodes before reaching the target. For example, in a path graph with 20,000 nodes, the new version is about 100× faster. These are the cases where the optimization has the most impact.

On a side note, with this experiment I learned that random graphs (erdos renyi) tend to have shortest paths with very few hops so they are not really good for benchmarking shortest-path algos. We can do a parallelism to randomized testing for graphs. Erdos renyi graphs can be good for catching obvious issues but to push algorithms and their corner cases some graph-generation engineering can sometimes be needed.

@rossbar

rossbar commented Jul 9, 2025

Copy link
Copy Markdown
Contributor

Thanks for updating the benchmarking results @amcandio ! They give me pause though: the speedups for the long paths are obvious and undisputed, but it also looks like there are real performance regressions for small, non-path-y graphs. IIUC, that would mean a significant performance hit for a user who were doing something like e.g.

for G in my_giant_list_of_relatively_small_graphs_with_say_10_nodes:
    nx.single_source_dijkstra(G, source=0, target=10)

Is that still the case?

@amcandio

Copy link
Copy Markdown
Contributor Author

Thanks for updating the benchmarking results @amcandio ! They give me pause though: the speedups for the long paths are obvious and undisputed, but it also looks like there are real performance regressions for small, non-path-y graphs. IIUC, that would mean a significant performance hit for a user who were doing something like e.g.

for G in my_giant_list_of_relatively_small_graphs_with_say_10_nodes:
    nx.single_source_dijkstra(G, source=0, target=10)

Is that still the case?

Yes, with very small graphs it might be slower (nanoseconds) but it doesn't look conclusive to me. There are examples with small graphs where it is faster. Could be a measurement error at that point.

In the case you mention you probably have other overheads impacting. Like creating those graphs is probably significantly slower than calling Dijkstra's.

I'm okay with this tradeoff. If those extra nanoseconds per call in small graphs are really a problem, you can cache the result. (unless you are creating graphs from scratch, in which case it is not the bottleneck).

Right now complexity is quadratical with respect to the shortest path length (in terms of hops). I believe having a suboptimal complexity so we can optimize for the small graphs is tuning it too much for one specific type of graph. This change makes that complexity linear, at the expense of some extra nanoseconds.

Note that the PR approach not only helps with path graphs but graphs where the shortest path has many hops. The harder Dijkstra's instances are the ones where you need to visit many hops to discover the shortest path, so this change makes those faster.

What do you think? The other alternative is having some specific ifs that do list copying for the first hops and then start doing predecessor reconstruction. But the code might not be as nice.

@dschult

dschult commented Jul 18, 2025

Copy link
Copy Markdown
Member

I don't see changes on the scale of nanoseconds. Am I looking in the wrong place (the shortest path benchmarking PR #8059 ) It seems like some cases are ms and 30% slower. I might be able to wrap my filter around that and swallow for the impressive gains elsewhere, but I want to make sure I am understanding the information we've already got in these two PRs.

@amcandio

Copy link
Copy Markdown
Contributor Author

I don't see changes on the scale of nanoseconds. Am I looking in the wrong place (the shortest path benchmarking PR #8059 ) It seems like some cases are ms and 30% slower. I might be able to wrap my filter around that and swallow for the impressive gains elsewhere, but I want to make sure I am understanding the information we've already got in these two PRs.

Right, in my previous message I was mostly talking about tiny graphs. I'm seeing mixed results with bigger random graphs. Those graphs tend to have a very short (in terms of hops) shortest path (especially if we pick a big p).

In that particular 33% example we can also see a big range in measurements (+-20ms) (Am I understanding this correctly?). Once I have my laptop back I can see what the shortest path looks like for this particular instance.

@amcandio

Copy link
Copy Markdown
Contributor Author

Now that I look at the +- variability everywhere. It could be that my poor Chromebook was struggling when I ran the benchmarks

@amcandio

Copy link
Copy Markdown
Contributor Author

@dschult so it definetely was my old Chromebook! I was running bencharking on a VM on a 2019 chromebook. Ran it with more respectable hardwarde (M1 chip) and I got:

(networkx-dev) bash-3.2$ asv compare 092f50e5 a1575792
Couldn't load asv.plugins._mamba_helpers because
No module named 'libmambapy'

All benchmarks:

| Change   | Before [092f50e5] <weighted_benchmarks~11>   | After [a1575792]    | Ratio   | Benchmark (Parameter)                                                                                                                        |
|----------|----------------------------------------------|---------------------|---------|----------------------------------------------------------------------------------------------------------------------------------------------|
|          | 3.56±0.03μs                                  | 3.61±0.07μs         | 1.02    | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('weighted_graph(42, gnp_random_graph, 10, 0.1, seed=42)')   |
|          | 8.29±0.04μs                                  | 8.03±0.03μs         | 0.97    | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('weighted_graph(42, gnp_random_graph, 10, 0.5, seed=42)')   |
|          | 9.22±0.03μs                                  | 8.76±0.02μs         | 0.95    | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('weighted_graph(42, gnp_random_graph, 10, 0.9, seed=42)')   |
|          | 166±0.4μs                                    | 157±2μs             | 0.95    | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('weighted_graph(42, gnp_random_graph, 100, 0.1, seed=42)')  |
|          | 589±4μs                                      | 551±1μs             | 0.94    | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('weighted_graph(42, gnp_random_graph, 100, 0.5, seed=42)')  |
|          | 531±0.9μs                                    | 490±3μs             | 0.92    | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('weighted_graph(42, gnp_random_graph, 100, 0.9, seed=42)')  |
|          | 14.7±1ms                                     | 11.4±0.06ms         | ~0.77   | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('weighted_graph(42, gnp_random_graph, 1000, 0.1, seed=42)') |
|          | 89.4±2ms                                     | 86.0±3ms            | 0.96    | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('weighted_graph(42, gnp_random_graph, 1000, 0.5, seed=42)') |
|          | 56.4±4ms                                     | 51.9±3ms            | 0.92    | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('weighted_graph(42, gnp_random_graph, 1000, 0.9, seed=42)') |
| -        | 1.31±0.1ms                                   | 490±2μs             | 0.37    | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('weighted_graph(42, path_graph, 1000)')                     |
| -        | 163±10ms                                     | 4.89±0.07ms         | 0.03    | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('weighted_graph(42, path_graph, 10000)')                    |
| -        | 569±20ms                                     | 9.81±0.03ms         | 0.02    | benchmark_algorithms.WeightedGraphBenchmark.time_weighted_single_source_dijkstra('weighted_graph(42, path_graph, 20000)')                    |

@jerrykcode

Copy link
Copy Markdown
Contributor

Hello everyone, I'm new to NetworkX and really appreciate these amazing implementations!

I think that for the all-targets case, there might be a simpler appraoch to optimize: we can record the path for each node only when it is popped from the priority queue (fringe). At that point, the shortest distance to the node has been determined, so we only need to copy the path once per node.

This avoids copying the path during every edge relaxation, and also eliminates the need to reconstruct paths at the end. In my opinion, this approach should be efficient for both dense and sparse graphs.

The code could look like this:

    pred_dict = pred
    if pred is None and paths is not None:
        pred_dict = {}
    
    G_succ = G._adj  # For speed-up (and works for both directed and undirected graphs)

    dist = {}  # dictionary of final distances
    seen = {}
    # fringe is heapq with 3-tuples (distance,c,node)
    # use the count c to avoid comparing nodes (may not be able to)
    c = count()
    fringe = []
    for source in sources:
        seen[source] = 0
        heappush(fringe, (0, next(c), source))
    while fringe:
        (d, _, v) = heappop(fringe)
        if v in dist:
            continue  # already searched this node.
        dist[v] = d
        if paths is not None and target is None: # need paths for all nodes
            if v in sources:
                paths[v] = [v] # in case the caller did not set paths[source] to source
            else:
                # copy only once for each node
                paths[v] = paths[pred_dict[v][0]] + [v]
        if v == target:
            break
        for u, e in G_succ[v].items():
            cost = weight(v, u, e)
            if cost is None:
                continue
            vu_dist = dist[v] + cost
            if cutoff is not None:
                if vu_dist > cutoff:
                    continue
            if u in dist:
                u_dist = dist[u]
                if vu_dist < u_dist:
                    raise ValueError("Contradictory paths found:", "negative weights?")
                elif pred is not None and vu_dist == u_dist:
                    pred[u].append(v)
            elif u not in seen or vu_dist < seen[u]:
                seen[u] = vu_dist
                heappush(fringe, (vu_dist, next(c), u))
                if paths is not None:
                    if target is not None:
                        paths[u] = paths[v] + [u]
                    #else No need to update paths here
                if pred is not None:
                    pred[u] = [v]
                elif pred_dict is not None:
                    pred_dict[u] = [v]
            elif vu_dist == seen[u]:
                if pred is not None:
                    pred[u].append(v)

    # No need to reconstruct paths if target is None

The core change is just these lines:

if v in sources:
    paths[v] = [v] # in case the caller did not set pred[source] to source
else:
    # copy only once for each node
    paths[v] = paths[pred_dict[v][0]] + [v]

and removes the copy at each edge relaxation.

@amcandio

Copy link
Copy Markdown
Contributor Author

Correct! A similar idea was proposed by @fei0319 earlier in the thread. I am planning on taking that one after we ship this one (wanted to limit the scope of PR to ease reviewing).

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

It looks like the latest timing results show this to uniformly speed up large graphs while not slowing smaller graphs. I haven't rerun those timing results on my machine, but I am OK with merging this and checking it when #8059 is merged.

Thanks @amcandio

@amcandio

Copy link
Copy Markdown
Contributor Author

It looks like the latest timing results show this to uniformly speed up large graphs while not slowing smaller graphs. I haven't rerun those timing results on my machine, but I am OK with merging this and checking it when #8059 is merged.

Thanks @amcandio

Thank you so much Dan! I'll address benchmarking PR's comments and then will do the followup optimization for multiple destinations.

@amcandio amcandio changed the title Optimizing Dijkstra's paths to target (~27x faster for graphs with multiple-hops shortest path) Optimizing Dijkstra's paths to target (~50x faster for graphs with multiple-hops shortest path) Jul 20, 2025

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

Thanks for re-running and sharing the updated results @amcandio ! I also added some benchmarks to explicitly test the "looping over a ton of small graphs" case, which confirms there is no performance degradation.

Thanks for sticking with it through the back-and-forth over benchmarks!

@rossbar
rossbar merged commit 544c324 into networkx:main Jul 24, 2025
@amcandio
amcandio deleted the dijkstras_paths_to_target branch July 24, 2025 13:47
@amcandio

Copy link
Copy Markdown
Contributor Author

Thank you so much! Will send the follow up optimizations later 🙂

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.

8 participants