Skip to content

Commit 38332e8

Browse files
authored
Merge pull request #18 from arran4/optimize-performCaseFirst-12956515176561281531
⚡ Optimize performCaseFirst using strings.Builder
2 parents b40a2cf + 07ac100 commit 38332e8

2 files changed

Lines changed: 27 additions & 1 deletion

File tree

perform_case_first_bench_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package strings2
2+
3+
import (
4+
"testing"
5+
"unicode"
6+
)
7+
8+
func BenchmarkPerformCaseFirst(b *testing.B) {
9+
s := "test"
10+
fn := unicode.ToUpper
11+
for i := 0; i < b.N; i++ {
12+
performCaseFirst(s, fn)
13+
}
14+
}
15+
16+
func BenchmarkPerformCaseFirst_Long(b *testing.B) {
17+
s := "teststringwithmorecharacters"
18+
fn := unicode.ToUpper
19+
for i := 0; i < b.N; i++ {
20+
performCaseFirst(s, fn)
21+
}
22+
}

types.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,11 @@ func performCaseFirst(s string, fn func(rune) rune) (string, rune, bool) {
5353
if r == u {
5454
return s, 0, true
5555
}
56-
return string(u) + s[size:], 0, true
56+
var b strings.Builder
57+
b.Grow(len(s) + utf8.UTFMax)
58+
b.WriteRune(u)
59+
b.WriteString(s[size:])
60+
return b.String(), 0, true
5761
}
5862

5963
// UpperCaseFirst uppercases the first character of the string.

0 commit comments

Comments
 (0)