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

Optimize Color::find_named_color() #75860

Merged
merged 1 commit into from
May 23, 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
25 changes: 13 additions & 12 deletions core/math/color.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
#include "color_names.inc"
#include "core/math/math_funcs.h"
#include "core/string/ustring.h"
#include "core/templates/rb_map.h"
#include "core/templates/hash_map.h"

#include "thirdparty/misc/ok_color.h"

Expand Down Expand Up @@ -414,31 +414,32 @@ Color Color::named(const String &p_name, const Color &p_default) {

int Color::find_named_color(const String &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.to_upper();

int idx = 0;
while (named_colors[idx].name != nullptr) {
if (name == String(named_colors[idx].name).replace("_", "")) {
return idx;
static HashMap<String, int> named_colors_hashmap;
if (unlikely(named_colors_hashmap.is_empty())) {
const int named_color_count = get_named_color_count();
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;
}

int Color::get_named_color_count() {
int idx = 0;
while (named_colors[idx].name != nullptr) {
idx++;
}
return idx;
return sizeof(named_colors) / sizeof(NamedColor);
}

String Color::get_named_color_name(int p_idx) {
Expand Down
1 change: 0 additions & 1 deletion core/math/color_names.inc
Original file line number Diff line number Diff line change
Expand Up @@ -189,5 +189,4 @@ static NamedColor named_colors[] = {
{ "WHITE_SMOKE", Color::hex(0xF5F5F5FF) },
{ "YELLOW", Color::hex(0xFFFF00FF) },
{ "YELLOW_GREEN", Color::hex(0x9ACD32FF) },
{ nullptr, Color() },
};
Loading