From f923cf7c5fa5f5d5bd3a2b6e12db372f188fc1f6 Mon Sep 17 00:00:00 2001 From: Technici4n <13494793+Technici4n@users.noreply.github.com> Date: Sun, 18 Aug 2024 19:41:07 +0200 Subject: [PATCH] Optimize ListCraftingInventory#extract (#8146) `removeZeros` is an O(n) operation. Use the newly introduced remove(AEKey) instead. --- src/main/java/appeng/api/stacks/KeyCounter.java | 15 +++++++++++++++ .../java/appeng/api/stacks/VariantCounter.java | 4 ++++ .../crafting/inv/ListCraftingInventory.java | 10 +++++++--- 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/src/main/java/appeng/api/stacks/KeyCounter.java b/src/main/java/appeng/api/stacks/KeyCounter.java index e9ffa79c1db..9f39ec67c59 100644 --- a/src/main/java/appeng/api/stacks/KeyCounter.java +++ b/src/main/java/appeng/api/stacks/KeyCounter.java @@ -94,10 +94,25 @@ public void add(AEKey key, long amount) { getSubIndex(key).add(key, amount); } + /** + * Subtracts the given amount from the value associated with the given key. + */ public void remove(AEKey key, long amount) { add(key, -amount); } + /** + * Removes the given key from this counter, and returns the old value (or 0). + */ + public long remove(AEKey key) { + var subIndex = getSubIndex(key); + var ret = subIndex.remove(key); + if (subIndex.isEmpty()) { + lists.remove(key.getPrimaryKey()); + } + return ret; + } + public void set(AEKey key, long amount) { getSubIndex(key).set(key, amount); } diff --git a/src/main/java/appeng/api/stacks/VariantCounter.java b/src/main/java/appeng/api/stacks/VariantCounter.java index 031f0254dcf..f6a68927cfa 100644 --- a/src/main/java/appeng/api/stacks/VariantCounter.java +++ b/src/main/java/appeng/api/stacks/VariantCounter.java @@ -42,6 +42,10 @@ public void set(AEKey key, long amount) { } } + public long remove(AEKey key) { + return getRecords().removeLong(key); + } + public void addAll(VariantCounter other) { for (var entry : other.getRecords().object2LongEntrySet()) { add(entry.getKey(), entry.getLongValue()); diff --git a/src/main/java/appeng/crafting/inv/ListCraftingInventory.java b/src/main/java/appeng/crafting/inv/ListCraftingInventory.java index 50066d7a5dc..7e9e109cfda 100644 --- a/src/main/java/appeng/crafting/inv/ListCraftingInventory.java +++ b/src/main/java/appeng/crafting/inv/ListCraftingInventory.java @@ -53,10 +53,14 @@ public void insert(AEKey what, long amount, Actionable mode) { @Override public long extract(AEKey what, long amount, Actionable mode) { - var extracted = Math.min(list.get(what), amount); + var available = list.get(what); + var extracted = Math.min(available, amount); if (mode == Actionable.MODULATE) { - list.remove(what, extracted); - list.removeZeros(); + if (available > extracted) { + list.remove(what, extracted); + } else { + list.remove(what); + } listener.onChange(what); } return extracted;