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

[3.x] Cache results for TranslationServer.compare_locales() #98234

Merged
merged 1 commit into from
Oct 17, 2024
Merged
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
40 changes: 27 additions & 13 deletions core/translation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -365,32 +365,46 @@ String TranslationServer::_standardize_locale(const String &p_locale, bool p_add
}

int TranslationServer::compare_locales(const String &p_locale_a, const String &p_locale_b) const {
if (p_locale_a == p_locale_b) {
// Exact match.
return 10;
}

const String cache_key = p_locale_a + "|" + p_locale_b;
const int *cached_result = locale_compare_cache.getptr(cache_key);
if (cached_result) {
return *cached_result;
}

String locale_a = _standardize_locale(p_locale_a, true);
String locale_b = _standardize_locale(p_locale_b, true);

if (locale_a == locale_b) {
// Exact match.
locale_compare_cache.set(cache_key, 10);
return 10;
}

Vector<String> locale_a_elements = locale_a.split("_");
Vector<String> locale_b_elements = locale_b.split("_");
if (locale_a_elements[0] == locale_b_elements[0]) {
// Matching language, both locales have extra parts.
// Return number of matching elements.
int matching_elements = 1;
for (int i = 1; i < locale_a_elements.size(); i++) {
for (int j = 1; j < locale_b_elements.size(); j++) {
if (locale_a_elements[i] == locale_b_elements[j]) {
matching_elements++;
}
}
}
return matching_elements;
} else {
if (locale_a_elements[0] != locale_b_elements[0]) {
// No match.
locale_compare_cache.set(cache_key, 0);
return 0;
}

// Matching language, both locales have extra parts.
// Return number of matching elements.
int matching_elements = 1;
for (int i = 1; i < locale_a_elements.size(); i++) {
for (int j = 1; j < locale_b_elements.size(); j++) {
if (locale_a_elements[i] == locale_b_elements[j]) {
matching_elements++;
}
}
}
locale_compare_cache.set(cache_key, matching_elements);
return matching_elements;
}

String TranslationServer::get_locale_name(const String &p_locale) const {
Expand Down
2 changes: 2 additions & 0 deletions core/translation.h
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ class TranslationServer : public Object {
Ref<Translation> tool_translation;
Ref<Translation> doc_translation;

mutable HashMap<String, int> locale_compare_cache;

bool enabled;

static TranslationServer *singleton;
Expand Down
Loading