Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

meta: Fix even fewer object creations #1165

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
package io.github.moulberry.notenoughupdates.core.config;

import io.github.moulberry.notenoughupdates.NotEnoughUpdates;
import io.github.moulberry.notenoughupdates.core.config.Position;
import io.github.moulberry.notenoughupdates.overlays.OverlayManager;
import io.github.moulberry.notenoughupdates.overlays.TextOverlay;
import io.github.moulberry.notenoughupdates.util.Utils;
Expand Down Expand Up @@ -78,7 +77,6 @@ public GuiPositionEditor(
});
}


this.positions = pos;
this.originalPositions = ogPos;
this.elementWidths = width;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,6 @@
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.List;
Expand Down Expand Up @@ -175,7 +174,7 @@ public void onRenderGameOverlayPost(RenderGameOverlayEvent.Post event) {
}
Utils.pushGuiScale(0);
GlStateManager.popMatrix();
OverlayManager.dontRenderOverlay = new ArrayList<>();
OverlayManager.dontRenderOverlay.clear();
}
if (Keyboard.isKeyDown(Keyboard.KEY_X)) {
NotificationHandler.notificationDisplayMillis = 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,10 @@
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.inventory.InventoryLargeChest;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IChatComponent;
import net.minecraftforge.event.entity.player.ItemTooltipEvent;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
Expand Down Expand Up @@ -169,8 +169,8 @@ public void onStackClick(SlotClickEvent event) {

@SubscribeEvent
public void replaceItem(ReplaceItemEvent event) {
IChatComponent chatComponent = event.getInventory().getDisplayName();
if (chatComponent == null || isWrongInventory()) return;
if (!(event.getInventory() instanceof InventoryLargeChest)) return;
if (isWrongInventory()) return;
ItemStack original = event.getOriginal();
if (original == null) return;
if (original.getItem() != Item.getItemFromBlock(Blocks.stained_glass_pane)) return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.IChatComponent;

import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
Expand All @@ -50,10 +52,13 @@ public class DamageCommas {
private static final Pattern PATTERN_NO_CRIT = Pattern.compile("(\u00a7.)([\\d+,]*)(.*)");
private static final Pattern OVERLOAD_PATTERN = Pattern.compile("(\u00a7.)" + OVERLOAD_STAR + "((?:\u00a7.[\\d,])+)(\u00a7.)" + OVERLOAD_STAR + "\u00a7r");

private static Map<String, IChatComponent> nameCache = new HashMap<>();

public static IChatComponent replaceName(EntityLivingBase entity) {
if (!entity.hasCustomName()) return entity.getDisplayName();
String rawName = entity.getName();
IChatComponent name = Utils.getOrPut(nameCache, rawName, entity::getDisplayName);
if (!entity.hasCustomName()) return name;
Comment on lines +58 to +60
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fairly sure this will just create more performance issues? It will increase RAM usage and it will decrease raw CPU performance.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fair point.
Should we rather avoid touching IChatComponent here then? as this still creates new objects on every call, filling up the gc quickly.


IChatComponent name = entity.getDisplayName();
if (!NotEnoughUpdates.INSTANCE.config.misc.damageIndicatorStyle2) return name;
if (!NotEnoughUpdates.INSTANCE.hasSkyblockScoreboard()) return name;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,7 @@ public boolean isRendering() {

private boolean isChestOverview(IInventory inventory) {
return chestNamePattern.matcher(StringUtils.cleanColour(
inventory.getDisplayName()
.getUnformattedText())).matches();
inventory.getName())).matches();
}

private boolean isChestOverview(GuiChest chest) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ public static CraftingRecipe parseCraftingRecipe(NEUManager manager, JsonObject
if (!recipe.has(name)) continue;
String item = recipe.get(name).getAsString();
if (item == null || item.isEmpty()) continue;
craftMatrix[i] = new Ingredient(manager, item);
craftMatrix[i] = Ingredient.ingredient(item);
}
int resultCount = 1;
if (recipe.has("count"))
Expand All @@ -162,6 +162,6 @@ public static CraftingRecipe parseCraftingRecipe(NEUManager manager, JsonObject
String outputItemId = outputItem.get("internalname").getAsString();
if (recipe.has("overrideOutputId"))
outputItemId = recipe.get("overrideOutputId").getAsString();
return new CraftingRecipe(manager, craftMatrix, new Ingredient(manager, outputItemId, resultCount), extra);
return new CraftingRecipe(manager, craftMatrix, Ingredient.ingredient(outputItemId, resultCount), extra);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ public EssenceUpgrades(
JsonObject jsonObject = entry.getValue().getAsJsonObject();
Gson gson = new Gson();

Ingredient output = new Ingredient(manager, internalName);
Ingredient output = Ingredient.ingredient(internalName);

if (!jsonObject.has("type")) {
System.err.println("Invalid essence entry for: " + internalName);
Expand Down Expand Up @@ -278,10 +278,7 @@ private List<RecipeSlot> buildSlotList() {
for (Map.Entry<String, Integer> requiredItem : tierUpgrade.getItemsRequired().entrySet()) {
ItemStack itemStack;
if (requiredItem.getKey().equals("SKYBLOCK_COIN")) {
Ingredient ingredient = Ingredient.coinIngredient(
manager,
requiredItem.getValue()
);
Ingredient ingredient = Ingredient.coinIngredient(requiredItem.getValue());
itemStack = ingredient.getItemStack();
} else {
itemStack = manager.createItemResolutionQuery().withKnownInternalName(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ static ForgeRecipe parseForgeRecipe(NEUManager manager, JsonObject recipe, JsonO
List<Ingredient> ingredients = new ArrayList<>();
for (JsonElement element : recipe.getAsJsonArray("inputs")) {
String ingredientString = element.getAsString();
ingredients.add(new Ingredient(manager, ingredientString));
ingredients.add(Ingredient.ingredient(ingredientString));
}
String internalItemId = output.get("internalname").getAsString();
if (recipe.has("overrideOutputId"))
Expand All @@ -226,7 +226,7 @@ static ForgeRecipe parseForgeRecipe(NEUManager manager, JsonObject recipe, JsonO
return new ForgeRecipe(
manager,
ingredients,
new Ingredient(manager, internalItemId, resultCount),
Ingredient.ingredient(internalItemId, resultCount),
duration,
hotmLevel
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,24 +21,38 @@

import com.google.gson.JsonObject;
import io.github.moulberry.notenoughupdates.NEUManager;
import io.github.moulberry.notenoughupdates.NotEnoughUpdates;
import io.github.moulberry.notenoughupdates.util.ItemUtils;
import io.github.moulberry.notenoughupdates.util.Utils;
import kotlin.Pair;
import net.minecraft.item.ItemStack;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;

public class Ingredient {

public static final String SKYBLOCK_COIN = "SKYBLOCK_COIN";
private final double count;
private final String internalItemId;
private final NEUManager manager;
private ItemStack itemStack;

private static final Map<String, Ingredient> itemCache = new HashMap<>();
private static final Map<Integer, Ingredient> itemCoinCache = new HashMap<>();
private static final Map<Pair<String, Double>, WeakReference<Ingredient>> itemAmountCache = new HashMap<>();

public static Ingredient ingredient(String ingredientIdentifier) {
return Utils.getOrPut(itemCache, ingredientIdentifier,
() -> new Ingredient(null, ingredientIdentifier)
);
}

// do not break SkyHanni
public Ingredient(NEUManager manager, String ingredientIdentifier) {
this.manager = manager;
String[] parts = ingredientIdentifier.split(":");
internalItemId = parts[0];
if (parts.length == 2) {
Expand All @@ -50,14 +64,20 @@ public Ingredient(NEUManager manager, String ingredientIdentifier) {
}
}

public Ingredient(NEUManager manager, String internalItemId, double count) {
this.manager = manager;
public static Ingredient ingredient(String ingredientIdentifier, double count) {
Supplier<WeakReference<Ingredient>> defaultValueSupplier = () ->
new WeakReference<>(new Ingredient(ingredientIdentifier, count)
);
Pair<String, Double> key = new Pair<>(ingredientIdentifier, count);
return Utils.getOrPut(itemAmountCache, key, defaultValueSupplier).get();
}

private Ingredient(String internalItemId, double count) {
this.count = count;
this.internalItemId = internalItemId;
}

private Ingredient(NEUManager manager, double coinValue) {
this.manager = manager;
private Ingredient(double coinValue) {
this.internalItemId = SKYBLOCK_COIN;
this.count = coinValue;
}
Expand All @@ -68,14 +88,16 @@ public static Set<Ingredient> mergeIngredients(Iterable<Ingredient> ingredients)
newIngredients.merge(
i.getInternalItemId(),
i,
(a, b) -> new Ingredient(i.manager, i.internalItemId, a.count + b.count)
(a, b) -> Ingredient.ingredient(i.internalItemId, a.count + b.count)
);
}
return new HashSet<>(newIngredients.values());
}

public static Ingredient coinIngredient(NEUManager manager, int coins) {
return new Ingredient(manager, coins);
public static Ingredient coinIngredient(int coins) {
return Utils.getOrPut(itemCoinCache, coins,
() -> new Ingredient(coins)
);
}

public boolean isCoins() {
Expand All @@ -95,6 +117,7 @@ public ItemStack getItemStack() {
if (isCoins()) {
return ItemUtils.getCoinItemStack(count);
}
NEUManager manager = NotEnoughUpdates.INSTANCE.manager;
JsonObject itemInfo = manager.getItemInformation().get(internalItemId);
itemStack = manager.jsonToStack(itemInfo);
itemStack.stackSize = (int) count;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -196,12 +196,12 @@ public ResourceLocation getBackground() {

public static NeuRecipe parseItemRecipe(NEUManager neuManager, JsonObject recipe, JsonObject outputItemJson) {
return new ItemShopRecipe(
new Ingredient(neuManager, outputItemJson.get("internalname").getAsString()),
Ingredient.ingredient(outputItemJson.get("internalname").getAsString()),
JsonUtils.transformJsonArrayToList(
recipe.getAsJsonArray("cost"),
it -> new Ingredient(neuManager, it.getAsString())
it -> Ingredient.ingredient(it.getAsString())
),
new Ingredient(neuManager, recipe.get("result").getAsString()),
Ingredient.ingredient(recipe.get("result").getAsString()),
outputItemJson
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,7 @@ public ResourceLocation getBackground() {
private static MobDrop parseMobDrop(NEUManager manager, JsonElement jsonElement) {
if (jsonElement.isJsonPrimitive()) {
return (new MobDrop(
new Ingredient(manager, jsonElement.getAsString()),
Ingredient.ingredient(jsonElement.getAsString()),
null,
Collections.emptyList(),
Collections.emptyList()
Expand All @@ -338,7 +338,7 @@ private static MobDrop parseMobDrop(NEUManager manager, JsonElement jsonElement)
JsonObject jsonObject = jsonElement.getAsJsonObject();
return (
new MobDrop(
new Ingredient(manager, jsonObject.get("id").getAsString()),
Ingredient.ingredient(jsonObject.get("id").getAsString()),
jsonObject.has("chance") ? jsonObject.get("chance").getAsString() : null,
JsonUtils.getJsonArrayOrEmpty(jsonObject, "extra", JsonElement::getAsString),
JsonUtils.getJsonArrayOrEmpty(jsonObject, "alternatives", element -> parseMobDrop(manager, element))
Expand All @@ -349,7 +349,7 @@ private static MobDrop parseMobDrop(NEUManager manager, JsonElement jsonElement)
public static MobLootRecipe parseRecipe(NEUManager manager, JsonObject recipe, JsonObject outputItemJson) {

return new MobLootRecipe(
new Ingredient(manager, outputItemJson.get("internalname").getAsString(), 1),
Ingredient.ingredient(outputItemJson.get("internalname").getAsString(), 1),
JsonUtils.getJsonArrayOrEmpty(recipe, "drops", element -> parseMobDrop(manager, element)),
recipe.has("level") ? recipe.get("level").getAsInt() : 0,
recipe.has("coins") ? recipe.get("coins").getAsInt() : 0,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ private void attemptToSaveBestiary(IInventory menu) {
Utils.addChatMessage("[WARNING] Could not parse drop, ambiguous or missing item information: " + loreLine);
continue;
}
Ingredient item = new Ingredient(neu.manager, possibleItems.get(0).get("internalname").getAsString());
Ingredient item = Ingredient.ingredient(possibleItems.get(0).get("internalname").getAsString());
String chance = loreMatcher.group("dropChances") != null
? loreMatcher.group("dropChances")
: loreMatcher.group("dropCount");
Expand All @@ -196,7 +196,7 @@ private void attemptToSaveBestiary(IInventory menu) {
}
}
recipes.add(new MobLootRecipe(
new Ingredient(neu.manager, internalMobName, 1),
Ingredient.ingredient(internalMobName, 1),
drops,
level,
coins,
Expand Down Expand Up @@ -277,9 +277,9 @@ public ForgeRecipe parseSingleForgeRecipe(IInventory chest) {
int coinCost = Integer.parseInt(
name.substring(0, name.length() - COINS_SUFFIX.length())
.replace(",", ""));
ingredient = Ingredient.coinIngredient(neu.manager, coinCost);
ingredient = Ingredient.coinIngredient(coinCost);
} else if (internalId != null) {
ingredient = new Ingredient(neu.manager, internalId, itemStack.stackSize);
ingredient = Ingredient.ingredient(internalId, itemStack.stackSize);
}
if (ingredient == null) continue;
if (col < 4) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,8 +172,8 @@ public ResourceLocation getBackground() {

public static VillagerTradeRecipe parseStaticRecipe(NEUManager manager, JsonObject recipe, JsonObject result) {
return new VillagerTradeRecipe(
new Ingredient(manager, recipe.get("result").getAsString()),
new Ingredient(manager, recipe.get("cost").getAsString()),
Ingredient.ingredient(recipe.get("result").getAsString()),
Ingredient.ingredient(recipe.get("cost").getAsString()),
recipe.has("min") ? recipe.get("min").getAsInt() : -1,
recipe.has("max") ? recipe.get("max").getAsInt() : -1
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,15 @@
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.BiFunction;

public class ItemUtils {
private static final Gson smallPrintingGson = new Gson();
private static final Map<Double, ItemStack> itemCache = new HashMap<>();

public static ItemStack createSkullItemStack(String displayName, String uuid, String skinAbsoluteUrl) {
JsonObject object = new JsonObject();
Expand All @@ -71,6 +73,10 @@ public static ItemStack createSkullItemStack(String displayName, String uuid, St
}

public static ItemStack getCoinItemStack(double coinAmount) {
return Utils.getOrPut(itemCache, coinAmount, () -> createCoinItemStack(coinAmount));
}

public static ItemStack createCoinItemStack(double coinAmount) {
String uuid = "2070f6cb-f5db-367a-acd0-64d39a7e5d1b";
String texture =
"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNTM4MDcxNzIxY2M1YjRjZDQwNmNlNDMxYTEzZjg2MDgzYTg5NzNlMTA2NGQyZjg4OTc4Njk5MzBlZTZlNTIzNyJ9fX0=";
Expand Down Expand Up @@ -412,14 +418,15 @@ public static ItemStack petToolTipXPExtendPetOverlay(ItemStack stack) {
int maxLvl = 100;
if (Constants.PETS != null && Constants.PETS.has("custom_pet_leveling") &&
Constants.PETS.getAsJsonObject("custom_pet_leveling").has(pet.petType.toUpperCase(Locale.ROOT)) &&
Constants.PETS.getAsJsonObject("custom_pet_leveling").getAsJsonObject(pet.petType.toUpperCase(Locale.ROOT)).has(
"max_level")) {
maxLvl =
Constants.PETS
.getAsJsonObject("custom_pet_leveling")
.getAsJsonObject(pet.petType.toUpperCase(Locale.ROOT))
.get("max_level")
.getAsInt();
Constants.PETS
.getAsJsonObject("custom_pet_leveling")
.getAsJsonObject(pet.petType.toUpperCase(Locale.ROOT))
.has("max_level")) {
maxLvl = Constants.PETS
.getAsJsonObject("custom_pet_leveling")
.getAsJsonObject(pet.petType.toUpperCase(Locale.ROOT))
.get("max_level")
.getAsInt();
}
for (int i = 0; i < lore.tagCount(); i++) {
if (i == lore.tagCount() - 2) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package io.github.moulberry.notenoughupdates.util;

import kotlin.Pair;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;

public class TwoKeyCache<K1, K2, V> {

private final Map<Pair<K1, K2>, V> cache = new HashMap<>();

public V getOrPut(K1 key1, K2 key2, Supplier<V> valueSupplier) {
Pair<K1, K2> realKey = new Pair<>(key1, key2);
V value = cache.get(realKey);
if (value == null) {
value = valueSupplier.get();
cache.put(realKey, value);
}
return value;
}
}
Loading
Loading