Browse Source

Optimize `Color::to_html` by allocating less.

Lukas Tenbrink 5 months ago
parent
commit
143f8e933e
3 changed files with 16 additions and 21 deletions
  1. 11 18
      core/math/color.cpp
  2. 3 0
      core/string/char_utils.h
  3. 2 3
      core/string/ustring.cpp

+ 11 - 18
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;
 }
 

+ 3 - 0
core/string/char_utils.h

@@ -36,6 +36,9 @@
 
 #include <iterator>
 
+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;             \

+ 2 - 3
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;
 		}
 	}