Reduce allocation slightly further

This commit is contained in:
Tony Garnock-Jones 2023-10-28 15:45:27 +02:00
parent f55fd2c668
commit 5401d2d8e9
1 changed files with 15 additions and 13 deletions

View File

@ -8,10 +8,9 @@ import java.util.logging.Logger;
public class Turn { public class Turn {
private final static AtomicLong nextHandle = new AtomicLong(0); private final static AtomicLong nextHandle = new AtomicLong(0);
private final static record SinglePending(Actor ac, List<Consumer<Turn>> actions) {}
private final Actor _actor; private final Actor _actor;
private SinglePending _singlePending = null; private Actor _pendingTarget = null;
private List<Consumer<Turn>> _pendingQ = null;
private Map<Actor, List<Consumer<Turn>>> _pending = null; private Map<Actor, List<Consumer<Turn>>> _pending = null;
private boolean _complete = false; private boolean _complete = false;
@ -45,10 +44,11 @@ public class Turn {
if (_pending != null) { if (_pending != null) {
_pending.forEach((ac, q) -> ac.execute(() -> Turn.forActor(ac, t -> q.forEach(f -> f.accept(t))))); _pending.forEach((ac, q) -> ac.execute(() -> Turn.forActor(ac, t -> q.forEach(f -> f.accept(t)))));
_pending = null; _pending = null;
} else if (_singlePending != null) { } else if (_pendingTarget != null) {
var ac = _singlePending.ac(); var ac = _pendingTarget;
var q = _singlePending.actions(); var q = _pendingQ;
_singlePending = null; _pendingTarget = null;
_pendingQ = null;
ac.execute(() -> Turn.forActor(ac, t -> q.forEach(f -> f.accept(t)))); ac.execute(() -> Turn.forActor(ac, t -> q.forEach(f -> f.accept(t))));
} }
_complete = true; _complete = true;
@ -63,17 +63,19 @@ public class Turn {
private void enqueue(Actor target, Consumer<Turn> action) { private void enqueue(Actor target, Consumer<Turn> action) {
if (_complete) throw new IllegalStateException("Attempt to reuse a committed Turn"); if (_complete) throw new IllegalStateException("Attempt to reuse a committed Turn");
if (_pending == null) { if (_pending == null) {
if (_singlePending == null) { if (_pendingTarget == null) {
_singlePending = new SinglePending(target, singletonList(action)); _pendingTarget = target;
_pendingQ = singletonList(action);
return; return;
} }
if (_singlePending.ac() == target) { if (_pendingTarget == target) {
_singlePending.actions().add(action); _pendingQ.add(action);
return; return;
} }
_pending = new HashMap<>(); _pending = new HashMap<>();
_pending.put(_singlePending.ac(), _singlePending.actions()); _pending.put(_pendingTarget, _pendingQ);
_singlePending = null; _pendingTarget = null;
_pendingQ = null;
} }
_pending.computeIfAbsent(target, k -> new LinkedList<>()).add(action); _pending.computeIfAbsent(target, k -> new LinkedList<>()).add(action);
} }