Skip to content

Commit

Permalink
crucial performance optimization
Browse files Browse the repository at this point in the history
  • Loading branch information
babbaj committed Oct 15, 2024
1 parent a690e1e commit 1e2ae34
Showing 1 changed file with 11 additions and 14 deletions.
25 changes: 11 additions & 14 deletions src/main/java/baritone/pathing/calc/Path.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import baritone.pathing.movement.Moves;
import baritone.pathing.path.CutoffPath;
import baritone.utils.pathing.PathBase;
import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.Collections;
Expand Down Expand Up @@ -77,27 +78,23 @@ class Path extends PathBase {
this.goal = goal;
this.context = context;
PathNode current = end;
LinkedList<BetterBlockPos> tempPath = new LinkedList<>();
LinkedList<PathNode> tempNodes = new LinkedList<>();
// Repeatedly inserting to the beginning of an arraylist is O(n^2)
// Instead, do it into a linked list, then convert at the end
List<BetterBlockPos> tempPath = new ArrayList<>();
List<PathNode> tempNodes = new ArrayList<>();
while (current != null) {
tempNodes.addFirst(current);
tempPath.addFirst(new BetterBlockPos(current.x, current.y, current.z));
tempNodes.add(current);
tempPath.add(new BetterBlockPos(current.x, current.y, current.z));
current = current.previous;
}
// If the position the player is at is different from the position we told A* to start from
if (!realStart.equals(startNodePos)) {
PathNode fakeNode = new PathNode(realStart.x, realStart.y, realStart.z, goal);
fakeNode.cost = 0;
tempNodes.addFirst(fakeNode);
tempPath.addFirst(realStart);
tempNodes.add(fakeNode);
tempPath.add(realStart);
}

// Can't directly convert from the PathNode pseudo linked list to an array because we don't know how long it is
// inserting into a LinkedList<E> keeps track of length, then when we addall (which calls .toArray) it's able
// to performantly do that conversion since it knows the length.
this.path = new ArrayList<>(tempPath);
this.nodes = new ArrayList<>(tempNodes);
// Nodes are traversed last to first so we need to reverse the list
this.path = Lists.reverse(tempPath);
this.nodes = Lists.reverse(tempNodes);
}

@Override
Expand Down

0 comments on commit 1e2ae34

Please sign in to comment.