Skip to content

Commit

Permalink
A minor performance improvement to A* and Dijkstra algorithms by avoi…
Browse files Browse the repository at this point in the history
…ding unnecessary dictionary lookups.
  • Loading branch information
renggli committed Dec 17, 2023
1 parent e8808eb commit 031fc8a
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
8 changes: 5 additions & 3 deletions lib/src/graph/algorithms/a_star_search.dart
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,12 @@ class _AStarSearchIterator<V> implements Iterator<Path<V, num>> {
for (final target in iterable.successorsOf(sourceState.vertex)) {
final value = iterable.edgeCost(sourceState.vertex, target);
final total = sourceState.total + value;
final targetState = states.putIfAbsent(
target, () => _State<V>(vertex: target, total: double.infinity));
final targetState =
states[target] ?? _State<V>(vertex: target, total: double.infinity);
if (total < targetState.total) {
if (targetState.total.isFinite) todo.remove(targetState);
targetState.total.isFinite
? todo.remove(targetState)
: states[target] = targetState;
targetState.parent = sourceState;
targetState.value = value;
targetState.total = total;
Expand Down
8 changes: 5 additions & 3 deletions lib/src/graph/algorithms/dijkstra_search.dart
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,12 @@ class _DijkstraSearchIterator<V> implements Iterator<Path<V, num>> {
for (final target in iterable.successorsOf(sourceState.vertex)) {
final value = iterable.edgeCost(sourceState.vertex, target);
final total = sourceState.total + value;
final targetState = states.putIfAbsent(
target, () => _State<V>(vertex: target, total: double.infinity));
final targetState =
states[target] ?? _State<V>(vertex: target, total: double.infinity);
if (total < targetState.total) {
if (targetState.total.isFinite) todo.remove(targetState);
targetState.total.isFinite
? todo.remove(targetState)
: states[target] = targetState;
targetState.parent = sourceState;
targetState.value = value;
targetState.total = total;
Expand Down

0 comments on commit 031fc8a

Please sign in to comment.