File size: 1,955 Bytes
e36aeda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package strings_test

import (
	. "strings"
	"testing"
)

func BenchmarkSplitSeqEmptySeparator(b *testing.B) {
	for range b.N {
		for range SplitSeq(benchInputHard, "") {
		}
	}
}

func BenchmarkSplitSeqSingleByteSeparator(b *testing.B) {
	for range b.N {
		for range SplitSeq(benchInputHard, "/") {
		}
	}
}

func BenchmarkSplitSeqMultiByteSeparator(b *testing.B) {
	for range b.N {
		for range SplitSeq(benchInputHard, "hello") {
		}
	}
}

func BenchmarkSplitAfterSeqEmptySeparator(b *testing.B) {
	for range b.N {
		for range SplitAfterSeq(benchInputHard, "") {
		}
	}
}

func BenchmarkSplitAfterSeqSingleByteSeparator(b *testing.B) {
	for range b.N {
		for range SplitAfterSeq(benchInputHard, "/") {
		}
	}
}

func BenchmarkSplitAfterSeqMultiByteSeparator(b *testing.B) {
	for range b.N {
		for range SplitAfterSeq(benchInputHard, "hello") {
		}
	}
}

func findKvBySplit(s string, k string) string {
	for _, kv := range Split(s, ",") {
		if HasPrefix(kv, k) {
			return kv
		}
	}
	return ""
}

func findKvBySplitSeq(s string, k string) string {
	for kv := range SplitSeq(s, ",") {
		if HasPrefix(kv, k) {
			return kv
		}
	}
	return ""
}

func BenchmarkSplitAndSplitSeq(b *testing.B) {
	testSplitString := "k1=v1,k2=v2,k3=v3,k4=v4"
	testCases := []struct {
		name  string
		input string
	}{
		{
			name:  "Key found",
			input: "k3",
		},
		{
			name:  "Key not found",
			input: "k100",
		},
	}

	for _, testCase := range testCases {
		b.Run("bySplit "+testCase.name, func(b *testing.B) {
			b.ResetTimer()
			b.ReportAllocs()
			for b.Loop() {
				findKvBySplit(testSplitString, testCase.input)
			}
		})

		b.Run("bySplitSeq "+testCase.name, func(b *testing.B) {
			b.ResetTimer()
			b.ReportAllocs()
			for b.Loop() {
				findKvBySplitSeq(testSplitString, testCase.input)
			}
		})
	}
}