Skip to content

Commit b40a2cf

Browse files
authored
Merge pull request #19 from arran4/perf-split-mix-case-alloc-17096859645213138563
⚡ Optimize splitMixCase buffer allocation
2 parents d6c51f4 + a5bbd10 commit b40a2cf

2 files changed

Lines changed: 21 additions & 1 deletion

File tree

benchmark_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,3 +166,18 @@ func BenchmarkToFormattedCase_Default(b *testing.B) {
166166
_ = ToFormattedCase(words)
167167
}
168168
}
169+
170+
func BenchmarkSplitMixCase(b *testing.B) {
171+
words := []Word{
172+
ExactCaseWord("thisIsAMixedCaseString"),
173+
ExactCaseWord("AnotherMixedCaseStringWithMoreParts"),
174+
ExactCaseWord("ShortOne"),
175+
ExactCaseWord("SuperLongMixedCaseStringWithManyManyCapitalLettersToTriggerReallocationIfBufferIsTooSmall"),
176+
}
177+
178+
b.ResetTimer()
179+
b.ReportAllocs()
180+
for i := 0; i < b.N; i++ {
181+
_, _ = WordsToFormattedCase(words, OptionMixCaseSupport(), OptionDelimiter("-"))
182+
}
183+
}

types.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -354,8 +354,13 @@ func separateOptionsAny(opts []any) ([]any, []any) {
354354

355355
// Helper function to split words in mixed case
356356
func splitMixCase(input, delimiter string) string {
357+
if delimiter == "" {
358+
return input
359+
}
357360
var result strings.Builder
358-
result.Grow(len(input))
361+
// Pre-allocate to avoid resizing.
362+
// We add a buffer for potential delimiters (assuming roughly 50% increase).
363+
result.Grow(len(input) + len(input)/2)
359364
for i, r := range input {
360365
if i > 0 && unicode.IsUpper(r) {
361366
result.WriteString(delimiter)

0 commit comments

Comments
 (0)