| 1 |
// Copyright 2024 The Go Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
package strings_test |
| 6 |
|
| 7 |
import ( |
| 8 |
. "strings" |
| 9 |
"testing" |
| 10 |
) |
| 11 |
|
| 12 |
func BenchmarkSplitSeqEmptySeparator(b *testing.B) { |
| 13 |
for range b.N { |
| 14 |
for range SplitSeq(benchInputHard, "") { |
| 15 |
} |
| 16 |
} |
| 17 |
} |
| 18 |
|
| 19 |
func BenchmarkSplitSeqSingleByteSeparator(b *testing.B) { |
| 20 |
for range b.N { |
| 21 |
for range SplitSeq(benchInputHard, "/") { |
| 22 |
} |
| 23 |
} |
| 24 |
} |
| 25 |
|
| 26 |
func BenchmarkSplitSeqMultiByteSeparator(b *testing.B) { |
| 27 |
for range b.N { |
| 28 |
for range SplitSeq(benchInputHard, "hello") { |
| 29 |
} |
| 30 |
} |
| 31 |
} |
| 32 |
|
| 33 |
func BenchmarkSplitAfterSeqEmptySeparator(b *testing.B) { |
| 34 |
for range b.N { |
| 35 |
for range SplitAfterSeq(benchInputHard, "") { |
| 36 |
} |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
func BenchmarkSplitAfterSeqSingleByteSeparator(b *testing.B) { |
| 41 |
for range b.N { |
| 42 |
for range SplitAfterSeq(benchInputHard, "/") { |
| 43 |
} |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
func BenchmarkSplitAfterSeqMultiByteSeparator(b *testing.B) { |
| 48 |
for range b.N { |
| 49 |
for range SplitAfterSeq(benchInputHard, "hello") { |
| 50 |
} |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
func findKvBySplit(s string, k string) string { |
| 55 |
for _, kv := range Split(s, ",") { |
| 56 |
if HasPrefix(kv, k) { |
| 57 |
return kv |
| 58 |
} |
| 59 |
} |
| 60 |
return "" |
| 61 |
} |
| 62 |
|
| 63 |
func findKvBySplitSeq(s string, k string) string { |
| 64 |
for kv := range SplitSeq(s, ",") { |
| 65 |
if HasPrefix(kv, k) { |
| 66 |
return kv |
| 67 |
} |
| 68 |
} |
| 69 |
return "" |
| 70 |
} |
| 71 |
|
| 72 |
func BenchmarkSplitAndSplitSeq(b *testing.B) { |
| 73 |
testSplitString := "k1=v1,k2=v2,k3=v3,k4=v4" |
| 74 |
testCases := []struct { |
| 75 |
name string |
| 76 |
input string |
| 77 |
}{ |
| 78 |
{ |
| 79 |
name: "Key found", |
| 80 |
input: "k3", |
| 81 |
}, |
| 82 |
{ |
| 83 |
name: "Key not found", |
| 84 |
input: "k100", |
| 85 |
}, |
| 86 |
} |
| 87 |
|
| 88 |
for _, testCase := range testCases { |
| 89 |
b.Run("bySplit "+testCase.name, func(b *testing.B) { |
| 90 |
b.ResetTimer() |
| 91 |
b.ReportAllocs() |
| 92 |
for b.Loop() { |
| 93 |
findKvBySplit(testSplitString, testCase.input) |
| 94 |
} |
| 95 |
}) |
| 96 |
|
| 97 |
b.Run("bySplitSeq "+testCase.name, func(b *testing.B) { |
| 98 |
b.ResetTimer() |
| 99 |
b.ReportAllocs() |
| 100 |
for b.Loop() { |
| 101 |
findKvBySplitSeq(testSplitString, testCase.input) |
| 102 |
} |
| 103 |
}) |
| 104 |
} |
| 105 |
} |