Skip to content

Commit

Permalink
Cache locales to avoid allocations (#952)
Browse files Browse the repository at this point in the history
Signed-off-by: Pablete1234 <[email protected]>
  • Loading branch information
Pablete1234 authored Jan 13, 2022
1 parent fa38f43 commit 6473510
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions util/src/main/java/tc/oc/pgm/util/text/TextTranslations.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<String, Locale> LOCALE_CACHE =
CacheBuilder.newBuilder()
.build(
new CacheLoader<String, Locale>() {
@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();
Expand Down Expand Up @@ -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());
}

/**
Expand Down

0 comments on commit 6473510

Please sign in to comment.