Optimize Color::find_named_color()

This commit is contained in:
Danil Alexeev 2023-04-09 17:40:58 +03:00
parent 8e2141eac5
commit 49594d8c41
No known key found for this signature in database
GPG Key ID: 124453E157DA8DC7
2 changed files with 13 additions and 13 deletions

View File

@ -33,7 +33,7 @@
#include "color_names.inc" #include "color_names.inc"
#include "core/math/math_funcs.h" #include "core/math/math_funcs.h"
#include "core/string/ustring.h" #include "core/string/ustring.h"
#include "core/templates/rb_map.h" #include "core/templates/hash_map.h"
#include "thirdparty/misc/ok_color.h" #include "thirdparty/misc/ok_color.h"
@ -414,7 +414,7 @@ Color Color::named(const String &p_name, const Color &p_default) {
int Color::find_named_color(const String &p_name) { int Color::find_named_color(const String &p_name) {
String name = p_name; String name = p_name;
// Normalize name // Normalize name.
name = name.replace(" ", ""); name = name.replace(" ", "");
name = name.replace("-", ""); name = name.replace("-", "");
name = name.replace("_", ""); name = name.replace("_", "");
@ -422,23 +422,24 @@ int Color::find_named_color(const String &p_name) {
name = name.replace(".", ""); name = name.replace(".", "");
name = name.to_upper(); name = name.to_upper();
int idx = 0; static HashMap<String, int> named_colors_hashmap;
while (named_colors[idx].name != nullptr) { if (unlikely(named_colors_hashmap.is_empty())) {
if (name == String(named_colors[idx].name).replace("_", "")) { const int named_color_count = get_named_color_count();
return idx; for (int i = 0; i < named_color_count; i++) {
named_colors_hashmap[String(named_colors[i].name).replace("_", "")] = i;
} }
idx++; }
const HashMap<String, int>::ConstIterator E = named_colors_hashmap.find(name);
if (E) {
return E->value;
} }
return -1; return -1;
} }
int Color::get_named_color_count() { int Color::get_named_color_count() {
int idx = 0; return sizeof(named_colors) / sizeof(NamedColor);
while (named_colors[idx].name != nullptr) {
idx++;
}
return idx;
} }
String Color::get_named_color_name(int p_idx) { String Color::get_named_color_name(int p_idx) {

View File

@ -189,5 +189,4 @@ static NamedColor named_colors[] = {
{ "WHITE_SMOKE", Color::hex(0xF5F5F5FF) }, { "WHITE_SMOKE", Color::hex(0xF5F5F5FF) },
{ "YELLOW", Color::hex(0xFFFF00FF) }, { "YELLOW", Color::hex(0xFFFF00FF) },
{ "YELLOW_GREEN", Color::hex(0x9ACD32FF) }, { "YELLOW_GREEN", Color::hex(0x9ACD32FF) },
{ nullptr, Color() },
}; };