Skip to content

Commit

Permalink
Optimize ListCraftingInventory#extract (#8146)
Browse files Browse the repository at this point in the history
`removeZeros` is an O(n) operation. Use the newly introduced
remove(AEKey) instead.
  • Loading branch information
Technici4n authored Aug 18, 2024
1 parent e6a2825 commit f923cf7
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 3 deletions.
15 changes: 15 additions & 0 deletions src/main/java/appeng/api/stacks/KeyCounter.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
4 changes: 4 additions & 0 deletions src/main/java/appeng/api/stacks/VariantCounter.java
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down
10 changes: 7 additions & 3 deletions src/main/java/appeng/crafting/inv/ListCraftingInventory.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit f923cf7

Please sign in to comment.