From 3919160e38000674ed967188510cce129f6bbcdd Mon Sep 17 00:00:00 2001 From: donutloop Date: Tue, 28 Dec 2021 03:04:15 +0100 Subject: [PATCH] Optimized: Capitalize (#4) * Use unicode.ToUpper func to convert first letter in string to upper case letter. * Preallocate memory with correct length and cap because the final string is not changing. --- strutil/string.go | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/strutil/string.go b/strutil/string.go index e0837e4..ff7541b 100644 --- a/strutil/string.go +++ b/strutil/string.go @@ -7,6 +7,7 @@ package strutil import ( "regexp" "strings" + "unicode" ) // CamelCase covert string to camelCase string. @@ -40,18 +41,16 @@ func Capitalize(s string) string { return "" } - res := "" - for i, v := range []rune(s) { + out := make([]rune, len(s)) + for i, v := range s { if i == 0 { - if v >= 97 && v <= 122 { - v -= 32 - } - res += string(v) + out[i] = unicode.ToUpper(v) } else { - res += strings.ToLower(string(v)) + out[i] = unicode.ToLower(v) } } - return res + + return string(out) } // LowerFirst converts the first character of string to lower case.