Skip to content

Commit

Permalink
Optimize copying m_scheduledCommands
Browse files Browse the repository at this point in the history
  • Loading branch information
kytpbs committed Oct 11, 2024
1 parent 7c7ca2e commit 896d784
Showing 1 changed file with 13 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ public static synchronized CommandScheduler getInstance() {

// A set of the currently-running commands.
private final Set<Command> m_scheduledCommands = new LinkedHashSet<>();
// A copy of the currently-running commands, used for iteration stored on class for caching
// purposes.
private Command[] m_scheduledCommandsCopy = new Command[12]; // 12 is arbitrary, it auto-resizes

// A map from required subsystems to their requiring commands. Also used as a set of the
// currently-required subsystems.
Expand Down Expand Up @@ -263,9 +266,16 @@ public void run() {

boolean isDisabled = RobotState.isDisabled();
// Run scheduled commands, remove finished commands.
for (Command command : Set.copyOf(m_scheduledCommands)) {
if (!isScheduled(command)) {
continue; // skip as the normal scheduledCommands was modified and that command was canceled
m_scheduledCommandsCopy = m_scheduledCommands.toArray(m_scheduledCommandsCopy);
for (Command command : m_scheduledCommandsCopy) {
if (command == null) {
// at least 1 Command was removed before `run` was called (diff between copy and original).
// No more elements to iterate over (see toArray documentation)
break;
}

if (!command.isScheduled()) {
continue; // Command was canceled in the previous iterations.
}

if (isDisabled && !command.runsWhenDisabled()) {
Expand Down

0 comments on commit 896d784

Please sign in to comment.