Reuse ItemExternalStorageCache to avoid excessive calls to getStackInSlot

This commit is contained in:
Anton Bulakh
2021-06-26 19:52:01 +03:00
parent 038661f5ee
commit 51bea520db
2 changed files with 15 additions and 14 deletions

View File

@@ -137,19 +137,7 @@ public class ItemExternalStorage implements IExternalStorage<ItemStack> {
@Override
public int getStored() {
IItemHandler handler = handlerSupplier.get();
if (handler == null) {
return 0;
}
int size = 0;
for (int i = 0; i < handler.getSlots(); ++i) {
size += handler.getStackInSlot(i).getCount();
}
return size;
return cache.getStored();
}
@Override

View File

@@ -11,24 +11,36 @@ import java.util.List;
public class ItemExternalStorageCache {
private List<ItemStack> cache;
private int stored = 0;
public int getStored() {
return stored;
}
public void update(INetwork network, @Nullable IItemHandler handler) {
if (handler == null) {
stored = 0;
return;
}
if (cache == null) {
cache = new ArrayList<>();
int stored = 0;
for (int i = 0; i < handler.getSlots(); ++i) {
cache.add(handler.getStackInSlot(i).copy());
ItemStack stack = handler.getStackInSlot(i).copy();
cache.add(stack);
stored += stack.getCount();
}
this.stored = stored;
return;
}
int stored = 0;
for (int i = 0; i < handler.getSlots(); ++i) {
ItemStack actual = handler.getStackInSlot(i);
stored += actual.getCount();
if (i >= cache.size()) { // ENLARGED
if (!actual.isEmpty()) {
@@ -69,6 +81,7 @@ public class ItemExternalStorageCache {
}
}
}
this.stored = stored;
if (cache.size() > handler.getSlots()) { // SHRUNK
for (int i = cache.size() - 1; i >= handler.getSlots(); --i) { // Reverse order for the remove call.