Cache results for TranslationServer.compare_locales()

(cherry picked from commit 7ebb63628d)
This commit is contained in:
Haoyu Qiu 2024-10-16 20:23:59 +08:00 committed by Rémi Verschelde
parent 45e30e4438
commit 6ba38858f6
No known key found for this signature in database
GPG key ID: C3336907360768E1
2 changed files with 29 additions and 13 deletions

View file

@ -359,17 +359,34 @@ String TranslationServer::standardize_locale(const String &p_locale) const {
} }
int TranslationServer::compare_locales(const String &p_locale_a, const String &p_locale_b) const { 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); String locale_a = standardize_locale(p_locale_a);
String locale_b = standardize_locale(p_locale_b); String locale_b = standardize_locale(p_locale_b);
if (locale_a == locale_b) { if (locale_a == locale_b) {
// Exact match. // Exact match.
locale_compare_cache.set(cache_key, 10);
return 10; return 10;
} }
Vector<String> locale_a_elements = locale_a.split("_"); Vector<String> locale_a_elements = locale_a.split("_");
Vector<String> locale_b_elements = locale_b.split("_"); Vector<String> locale_b_elements = locale_b.split("_");
if (locale_a_elements[0] == locale_b_elements[0]) { 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. // Matching language, both locales have extra parts.
// Return number of matching elements. // Return number of matching elements.
int matching_elements = 1; int matching_elements = 1;
@ -380,11 +397,8 @@ int TranslationServer::compare_locales(const String &p_locale_a, const String &p
} }
} }
} }
locale_compare_cache.set(cache_key, matching_elements);
return matching_elements; return matching_elements;
} else {
// No match.
return 0;
}
} }
String TranslationServer::get_locale_name(const String &p_locale) const { String TranslationServer::get_locale_name(const String &p_locale) const {

View file

@ -87,6 +87,8 @@ class TranslationServer : public Object {
Ref<Translation> tool_translation; Ref<Translation> tool_translation;
Ref<Translation> doc_translation; Ref<Translation> doc_translation;
mutable HashMap<String, int> locale_compare_cache;
bool enabled; bool enabled;
static TranslationServer *singleton; static TranslationServer *singleton;