From 6473510254f79975c7df517f1256866948df9e99 Mon Sep 17 00:00:00 2001 From: Pablo Herrera Date: Thu, 13 Jan 2022 21:58:20 +0100 Subject: [PATCH] Cache locales to avoid allocations (#952) Signed-off-by: Pablete1234 --- .../tc/oc/pgm/util/text/TextTranslations.java | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/util/src/main/java/tc/oc/pgm/util/text/TextTranslations.java b/util/src/main/java/tc/oc/pgm/util/text/TextTranslations.java index 4c103b62b1..29c25b7cee 100644 --- a/util/src/main/java/tc/oc/pgm/util/text/TextTranslations.java +++ b/util/src/main/java/tc/oc/pgm/util/text/TextTranslations.java @@ -5,6 +5,9 @@ import static net.kyori.adventure.text.Component.text; import static net.kyori.adventure.text.Component.translatable; +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.CacheLoader; +import com.google.common.cache.LoadingCache; import com.google.common.collect.ImmutableList; import com.google.common.collect.Table; import com.google.common.collect.Tables; @@ -44,6 +47,16 @@ private TextTranslations() {} // Locale of the source code .properties files private static final Locale SOURCE_LOCALE = Locale.US; + // Cache locales to avoid allocating many locales per player & message + private static final LoadingCache LOCALE_CACHE = + CacheBuilder.newBuilder() + .build( + new CacheLoader() { + @Override + public Locale load(@NotNull String str) { + return parseLocale(str); + } + }); // A control to ensure that .properties are loaded in UTF-8 format private static final UTF8Control SOURCE_CONTROL = new UTF8Control(); @@ -260,10 +273,8 @@ private static java.util.Locale parseLocale(String locale) { } public static Locale getLocale(@Nullable CommandSender sender) { - if (sender == null || !(sender instanceof Player)) { - return SOURCE_LOCALE; - } - return parseLocale(((Player) sender).spigot().getLocale()); + if (!(sender instanceof Player)) return SOURCE_LOCALE; + return LOCALE_CACHE.getUnchecked(((Player) sender).spigot().getLocale()); } /**