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

Cache locales to avoid allocations #952

Merged
merged 1 commit into from
Jan 13, 2022
Merged
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
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