From 143f8e933e3e193ec23eb2cb8c17779bda099128 Mon Sep 17 00:00:00 2001 From: Lukas Tenbrink Date: Thu, 20 Mar 2025 02:02:25 +0100 Subject: [PATCH] Optimize `Color::to_html` by allocating less. --- core/math/color.cpp | 29 +++++++++++------------------ core/string/char_utils.h | 3 +++ core/string/ustring.cpp | 5 ++--- 3 files changed, 16 insertions(+), 21 deletions(-) diff --git a/core/math/color.cpp b/core/math/color.cpp index cb41eb94efb..d75a33f6a15 100644 --- a/core/math/color.cpp +++ b/core/math/color.cpp @@ -109,36 +109,29 @@ uint64_t Color::to_rgba64() const { return c; } -String _to_hex(float p_val) { +void _append_hex(float p_val, char32_t *string) { int v = Math::round(p_val * 255.0f); v = CLAMP(v, 0, 255); - String ret; for (int i = 0; i < 2; i++) { - char32_t c[2] = { 0, 0 }; - int lv = v & 0xF; - if (lv < 10) { - c[0] = '0' + lv; - } else { - c[0] = 'a' + lv - 10; - } - + string[i] = hex_char_table_lower[v & 0xF]; v >>= 4; - String cs = (const char32_t *)c; - ret = cs + ret; } - - return ret; } String Color::to_html(bool p_alpha) const { String txt; - txt += _to_hex(r); - txt += _to_hex(g); - txt += _to_hex(b); + txt.resize(p_alpha ? 9 : 7); + char32_t *ptr = txt.ptrw(); + + _append_hex(r, ptr + 0); + _append_hex(g, ptr + 2); + _append_hex(b, ptr + 4); if (p_alpha) { - txt += _to_hex(a); + _append_hex(a, ptr + 6); } + ptr[txt.size() - 1] = '\0'; + return txt; } diff --git a/core/string/char_utils.h b/core/string/char_utils.h index 68e783c48af..9c632e52520 100644 --- a/core/string/char_utils.h +++ b/core/string/char_utils.h @@ -36,6 +36,9 @@ #include +static constexpr char hex_char_table_upper[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; +static constexpr char hex_char_table_lower[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; + #define BSEARCH_CHAR_RANGE(m_array) \ int low = 0; \ int high = std::size(m_array) - 1; \ diff --git a/core/string/ustring.cpp b/core/string/ustring.cpp index 00a2d4b2bb6..6fa87093886 100644 --- a/core/string/ustring.cpp +++ b/core/string/ustring.cpp @@ -4736,9 +4736,8 @@ String String::uri_encode() const { res += ord; } else { char p[4] = { '%', 0, 0, 0 }; - static const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; - p[1] = hex[ord >> 4]; - p[2] = hex[ord & 0xF]; + p[1] = hex_char_table_upper[ord >> 4]; + p[2] = hex_char_table_upper[ord & 0xF]; res += p; } }