Browse Source

Cache results for `TranslationServer.compare_locales()`

Haoyu Qiu 9 months ago
parent
commit
acab2d6c1c
2 changed files with 24 additions and 13 deletions
  1. 22 13
      core/string/translation_server.cpp
  2. 2 0
      core/string/translation_server.h

+ 22 - 13
core/string/translation_server.cpp

@@ -228,32 +228,41 @@ int TranslationServer::compare_locales(const String &p_locale_a, const String &p
 		return 10;
 		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_a = _standardize_locale(p_locale_a, true);
 	String locale_b = _standardize_locale(p_locale_b, true);
 	String locale_b = _standardize_locale(p_locale_b, true);
 
 
 	if (locale_a == locale_b) {
 	if (locale_a == locale_b) {
 		// Exact match.
 		// Exact match.
+		locale_compare_cache.insert(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]) {
-		// 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.
 		// No match.
+		locale_compare_cache.insert(cache_key, 0);
 		return 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.insert(cache_key, matching_elements);
+	return matching_elements;
 }
 }
 
 
 String TranslationServer::get_locale_name(const String &p_locale) const {
 String TranslationServer::get_locale_name(const String &p_locale) const {

+ 2 - 0
core/string/translation_server.h

@@ -46,6 +46,8 @@ class TranslationServer : public Object {
 	Ref<TranslationDomain> doc_domain;
 	Ref<TranslationDomain> doc_domain;
 	HashMap<StringName, Ref<TranslationDomain>> custom_domains;
 	HashMap<StringName, Ref<TranslationDomain>> custom_domains;
 
 
+	mutable HashMap<String, int> locale_compare_cache;
+
 	bool enabled = true;
 	bool enabled = true;
 
 
 	static TranslationServer *singleton;
 	static TranslationServer *singleton;