Debian Codegraph @

internal/benchtest/benchtest_test.go

raw
1 package benchtest
2
3 import (
4 "errors"
5 "flag"
6 "fmt"
7 "math/rand"
8 "regexp"
9 "regexp/syntax"
10 "strings"
11 "testing"
12 "unicode"
13 "unicode/utf8"
14
15 "github.com/charlievieth/strcase"
16 )
17
18 var benchStdLib = flag.Bool("stdlib", false,
19 "Use the stdlib's strings package instead of strcase (for comparison)")
20
21 var benchLower = flag.Bool("stdlib-case", false,
22 "Convert case with strings.ToUpper before using the stdlib's strings package")
23
24 var benchRegexp = flag.Bool("regexp", false,
25 "Use the regexp package for matching (for comparison).")
26
27 func recoverCompileError(b *testing.B) {
28 if e := recover(); e != nil {
29 err, ok := e.(error)
30 if !ok {
31 panic(fmt.Sprintf("HERE: %#v\n", e))
32 }
33 var serr *syntax.Error
34 if !errors.As(err, &serr) {
35 panic(e)
36 }
37 b.Skip("skipping: error compiling regexp:", serr)
38 }
39 }
40
41 func mustCompile(b *testing.B, expr string) *regexp.Regexp {
42 re, err := regexp.Compile(expr)
43 if err != nil {
44 b.Skip("skipping: cannot compile regexp:", err)
45 }
46 return re
47 }
48
49 func benchIndexRune(b *testing.B, s string, r rune) {
50 n := strings.IndexRune(s, r)
51 if n != strcase.IndexRune(s, r) {
52 b.Fatal("Invalid benchmark: strings/strcase results are not equal")
53 }
54 if n >= 0 {
55 b.SetBytes(int64(n + utf8.RuneLen(r)))
56 } else {
57 b.SetBytes(int64(len(s)))
58 }
59 switch {
60 case *benchStdLib:
61 for i := 0; i < b.N; i++ {
62 strings.IndexRune(s, r)
63 }
64 case *benchLower:
65 for i := 0; i < b.N; i++ {
66 strings.IndexRune(strings.ToUpper(s), unicode.ToUpper(r))
67 }
68 case *benchRegexp:
69 defer recoverCompileError(b)
70 for i := 0; i < b.N; i++ {
71 mustCompile(b, `(?i)`+string(r)).FindStringIndex(s)
72 }
73 default:
74 for i := 0; i < b.N; i++ {
75 strcase.IndexRune(s, r)
76 }
77 }
78 }
79
80 func benchIndex(b *testing.B, s, substr string) {
81 if strings.Index(s, substr) != strcase.Index(s, substr) {
82 b.Fatal("Invalid benchmark: strings/strcase results are not equal")
83 }
84 setBytes := func(fn func(s, substr string) int) {
85 n := fn(s, substr)
86 if n >= 0 {
87 b.SetBytes(int64(n + len(substr)))
88 } else {
89 b.SetBytes(int64(len(s)))
90 }
91 }
92 switch {
93 case *benchStdLib:
94 setBytes(strings.Index)
95 for i := 0; i < b.N; i++ {
96 strings.Index(s, substr)
97 }
98 case *benchLower:
99 setBytes(func(s, substr string) int {
100 return strings.Index(strings.ToUpper(s), strings.ToUpper(substr))
101 })
102 for i := 0; i < b.N; i++ {
103 strings.Index(strings.ToUpper(s), strings.ToUpper(substr))
104 }
105 case *benchRegexp:
106 defer recoverCompileError(b)
107 for i := 0; i < b.N; i++ {
108 mustCompile(b, `(?i)`+regexp.QuoteMeta(substr)).FindStringIndex(s)
109 }
110 default:
111 setBytes(strcase.Index)
112 for i := 0; i < b.N; i++ {
113 strcase.Index(s, substr)
114 }
115 }
116 }
117
118 func benchIndexByte(b *testing.B, s string, c byte) {
119 n := strings.IndexByte(s, c)
120 if n != strcase.IndexByte(s, c) {
121 b.Fatal("Invalid benchmark: strings/strcase results are not equal")
122 }
123 if n >= 0 {
124 b.SetBytes(int64(n + 1))
125 } else {
126 b.SetBytes(int64(len(s)))
127 }
128 switch {
129 case *benchStdLib:
130 for i := 0; i < b.N; i++ {
131 strings.IndexByte(s, c)
132 }
133 case *benchLower:
134 for i := 0; i < b.N; i++ {
135 strings.IndexByte(strings.ToUpper(s), byte(unicode.ToUpper(rune(c))))
136 }
137 case *benchRegexp:
138 b.Skip("skipping: benchmark not supported with -regexp flag")
139 default:
140 for i := 0; i < b.N; i++ {
141 strcase.IndexByte(s, c)
142 }
143 }
144 }
145
146 func benchLastIndex(b *testing.B, s, substr string) {
147 n := strings.LastIndex(s, substr)
148 if n != strcase.LastIndex(s, substr) {
149 b.Fatal("Invalid benchmark: strings/strcase results are not equal")
150 }
151 if n >= 0 {
152 b.SetBytes(int64(len(s) - n))
153 } else {
154 b.SetBytes(int64(len(s)))
155 }
156 switch {
157 case *benchStdLib:
158 for i := 0; i < b.N; i++ {
159 strings.LastIndex(s, substr)
160 }
161 case *benchLower:
162 for i := 0; i < b.N; i++ {
163 strings.LastIndex(strings.ToUpper(s), strings.ToUpper(substr))
164 }
165 case *benchRegexp:
166 b.Skip("skipping: benchmark not supported with -regexp flag")
167 default:
168 for i := 0; i < b.N; i++ {
169 strcase.LastIndex(s, substr)
170 }
171 }
172 }
173
174 func benchEqualFold(b *testing.B, s1, s2 string) {
175 ok := strings.EqualFold(s1, s2)
176 if !ok || ok != strcase.EqualFold(s1, s2) {
177 b.Fatal("Invalid benchmark: strings/strcase results are not equal")
178 }
179 if len(s1) > len(s2) {
180 b.SetBytes(int64(len(s1)))
181 } else {
182 b.SetBytes(int64(len(s2)))
183 }
184 switch {
185 case *benchStdLib:
186 for i := 0; i < b.N; i++ {
187 strings.EqualFold(s1, s2)
188 }
189 case *benchLower:
190 b.Skip("skipping: benchmark not relevant with -stdlib-case flag")
191 case *benchRegexp:
192 defer recoverCompileError(b)
193 for i := 0; i < b.N; i++ {
194 mustCompile(b, `(?i)^`+regexp.QuoteMeta(s1)+`$`).FindStringIndex(s2)
195 }
196 default:
197 for i := 0; i < b.N; i++ {
198 strcase.EqualFold(s1, s2)
199 }
200 }
201 }
202
203 func benchCount(b *testing.B, s, substr string) {
204 if strings.Count(s, substr) != strcase.Count(s, substr) {
205 b.Fatal("Invalid benchmark: strings/strcase results are not equal")
206 }
207 b.SetBytes(int64(len(s)))
208 switch {
209 case *benchStdLib:
210 for i := 0; i < b.N; i++ {
211 strings.Count(s, substr)
212 }
213 case *benchLower:
214 for i := 0; i < b.N; i++ {
215 strings.Count(strings.ToUpper(s), strings.ToUpper(substr))
216 }
217 case *benchRegexp:
218 defer recoverCompileError(b)
219 for i := 0; i < b.N; i++ {
220 mustCompile(b, `(?i)`+regexp.QuoteMeta(substr)).FindAllStringSubmatchIndex(s, -1)
221 }
222 default:
223 for i := 0; i < b.N; i++ {
224 strcase.Count(s, substr)
225 }
226 }
227 }
228
229 func benchIndexAny(b *testing.B, s, cutset string) {
230 if strings.IndexAny(s, cutset) != strcase.IndexAny(s, cutset) {
231 b.Fatal("Invalid benchmark: strings/strcase results are not equal")
232 }
233 switch {
234 case *benchStdLib:
235 for i := 0; i < b.N; i++ {
236 strings.IndexAny(s, cutset)
237 }
238 case *benchLower:
239 for i := 0; i < b.N; i++ {
240 strings.IndexAny(strings.ToUpper(s), strings.ToUpper(cutset))
241 }
242 case *benchRegexp:
243 defer recoverCompileError(b)
244 for i := 0; i < b.N; i++ {
245 // Convert cutset "abc" => `(a|b|c)`
246 mustCompile(b,
247 `(?i)(`+strings.Join(strings.Split(cutset, ""), "|")+`)`,
248 ).FindStringIndex(s)
249 }
250 default:
251 for i := 0; i < b.N; i++ {
252 strcase.IndexAny(s, cutset)
253 }
254 }
255 }
256
257 func benchLastIndexAny(b *testing.B, s, cutset string) {
258 if strings.LastIndexAny(s, cutset) != strcase.LastIndexAny(s, cutset) {
259 b.Fatal("Invalid benchmark: strings/strcase results are not equal")
260 }
261 switch {
262 case *benchStdLib:
263 for i := 0; i < b.N; i++ {
264 strings.LastIndexAny(s, cutset)
265 }
266 case *benchLower:
267 for i := 0; i < b.N; i++ {
268 strings.LastIndexAny(strings.ToUpper(s), strings.ToUpper(cutset))
269 }
270 case *benchRegexp:
271 b.Skip("skipping: benchmark not supported with -regexp flag")
272 default:
273 for i := 0; i < b.N; i++ {
274 strcase.LastIndexAny(s, cutset)
275 }
276 }
277 }
278
279 // The below benchmarks are from src/strings/strings_test.go
280
281 const benchmarkString = "some_text=some☺value"
282
283 func BenchmarkIndexRune(b *testing.B) {
284 if got := strings.IndexRune(benchmarkString, '☺'); got != 14 {
285 b.Fatalf("wrong index: expected 14, got=%d", got)
286 }
287 benchIndexRune(b, benchmarkString, '☺')
288 }
289
290 var benchmarkLongString = strings.Repeat(" ", 100) + benchmarkString
291
292 func BenchmarkIndexRuneLongString(b *testing.B) {
293 if got := strings.IndexRune(benchmarkLongString, '☺'); got != 114 {
294 b.Fatalf("wrong index: expected 114, got=%d", got)
295 }
296 benchIndexRune(b, benchmarkLongString, '☺')
297 }
298
299 func BenchmarkIndexRuneFastPath(b *testing.B) {
300 if got := strings.IndexRune(benchmarkString, 'v'); got != 17 {
301 b.Fatalf("wrong index: expected 17, got=%d", got)
302 }
303 benchIndexRune(b, benchmarkString, 'v')
304 }
305
306 func BenchmarkIndex(b *testing.B) {
307 if got := strings.Index(benchmarkString, "v"); got != 17 {
308 b.Fatalf("wrong index: expected 17, got=%d", got)
309 }
310 benchIndex(b, benchmarkString, "v")
311 }
312
313 func BenchmarkLastIndex(b *testing.B) {
314 if got := strings.Index(benchmarkString, "v"); got != 17 {
315 b.Fatalf("wrong index: expected 17, got=%d", got)
316 }
317 benchLastIndex(b, benchmarkString, "v")
318 }
319
320 func BenchmarkIndexByte(b *testing.B) {
321 if got := strings.IndexByte(benchmarkString, 'v'); got != 17 {
322 b.Fatalf("wrong index: expected 17, got=%d", got)
323 }
324 benchIndexByte(b, benchmarkString, 'v')
325 }
326
327 func BenchmarkEqualFold(b *testing.B) {
328 const s1 = "abcdefghijKz"
329 const s2 = "abcDefGhijKz"
330
331 b.Run("ASCII", func(b *testing.B) {
332 benchEqualFold(b, s1, s2)
333 })
334
335 b.Run("UnicodePrefix", func(b *testing.B) {
336 benchEqualFold(b, "αβδ"+s1, "ΑΒΔ"+s2)
337 })
338
339 b.Run("UnicodeSuffix", func(b *testing.B) {
340 benchEqualFold(b, s1+"αβδ", s2+"ΑΒΔ")
341 })
342 }
343
344 func makeBenchInputHard() string {
345 tokens := [...]string{
346 "<a>", "<p>", "<b>", "<strong>",
347 "</a>", "</p>", "</b>", "</strong>",
348 "hello", "world",
349 }
350 x := make([]byte, 0, 1<<20)
351 for {
352 i := rand.Intn(len(tokens))
353 if len(x)+len(tokens[i]) >= 1<<20 {
354 break
355 }
356 x = append(x, tokens[i]...)
357 }
358 return string(x)
359 }
360
361 var benchInputHard = makeBenchInputHard()
362
363 func benchmarkIndexHard(b *testing.B, sep string) {
364 benchIndex(b, benchInputHard, sep)
365 }
366
367 func benchmarkLastIndexHard(b *testing.B, sep string) {
368 benchLastIndex(b, benchInputHard, sep)
369 }
370
371 func benchmarkCountHard(b *testing.B, sep string) {
372 benchCount(b, benchInputHard, sep)
373 }
374
375 func BenchmarkIndexHard1(b *testing.B) { benchmarkIndexHard(b, "<>") }
376 func BenchmarkIndexHard2(b *testing.B) { benchmarkIndexHard(b, "</pre>") }
377 func BenchmarkIndexHard3(b *testing.B) { benchmarkIndexHard(b, "<b>hello world</b>") }
378 func BenchmarkIndexHard4(b *testing.B) {
379 benchmarkIndexHard(b, "<pre><b>hello</b><strong>world</strong></pre>")
380 }
381
382 func BenchmarkLastIndexHard1(b *testing.B) { benchmarkLastIndexHard(b, "<>") }
383 func BenchmarkLastIndexHard2(b *testing.B) { benchmarkLastIndexHard(b, "</pre>") }
384 func BenchmarkLastIndexHard3(b *testing.B) { benchmarkLastIndexHard(b, "<b>hello world</b>") }
385
386 func BenchmarkCountHard1(b *testing.B) { benchmarkCountHard(b, "<>") }
387 func BenchmarkCountHard2(b *testing.B) { benchmarkCountHard(b, "</pre>") }
388 func BenchmarkCountHard3(b *testing.B) { benchmarkCountHard(b, "<b>hello world</b>") }
389
390 var benchInputTorture = strings.Repeat("ABC", 1<<10) + "123" + strings.Repeat("ABC", 1<<10)
391 var benchNeedleTorture = strings.Repeat("ABC", 1<<10+1)
392
393 func BenchmarkIndexTorture(b *testing.B) {
394 benchIndex(b, benchInputTorture, benchNeedleTorture)
395 }
396
397 func BenchmarkCountTorture(b *testing.B) {
398 benchCount(b, benchInputTorture, benchNeedleTorture)
399 }
400
401 func BenchmarkCountTortureOverlapping(b *testing.B) {
402 A := strings.Repeat("ABC", 1<<20)
403 B := strings.Repeat("ABC", 1<<10)
404 benchCount(b, A, B)
405 }
406
407 // NB: we count "a" instead of "=" here, which differs from the stdlib
408 // but is a more accurate benchmark since for non-Alpha ASCII chars we
409 // use strings.Count.
410 func BenchmarkCountByte(b *testing.B) {
411 if strcase.Count(benchmarkString, "a") != 1 {
412 b.Fatalf("strcase.Count(%q, %q) != 1", benchmarkString, "a")
413 }
414 indexSizes := []int{10, 32, 4 << 10, 4 << 20, 64 << 20}
415 benchStr := strings.Repeat(benchmarkString,
416 (indexSizes[len(indexSizes)-1]+len(benchmarkString)-1)/len(benchmarkString))
417 benchFunc := func(b *testing.B, benchStr string) {
418 b.SetBytes(int64(len(benchStr)))
419 benchCount(b, benchStr, "a") // NB: "a" instead of "="
420 }
421 for _, size := range indexSizes {
422 b.Run(valName(size), func(b *testing.B) {
423 benchFunc(b, benchStr[:size])
424 })
425 }
426 }
427
428 func BenchmarkIndexAnyASCII(b *testing.B) {
429 x := strings.Repeat("#", 2048) // Never matches set
430 cs := "0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz"
431 for k := 1; k <= 2048; k <<= 4 {
432 for j := 1; j <= 64; j <<= 1 {
433 b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
434 benchIndexAny(b, x[:k], cs[:j])
435 })
436 }
437 }
438 }
439
440 func BenchmarkIndexAnyUTF8(b *testing.B) {
441 x := strings.Repeat("#", 2048) // Never matches set
442 cs := "你好世界, hello world. 你好世界, hello world. 你好世界, hello world."
443 for k := 1; k <= 2048; k <<= 4 {
444 for j := 1; j <= 64; j <<= 1 {
445 b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
446 benchIndexAny(b, x[:k], cs[:j])
447 })
448 }
449 }
450 }
451
452 func BenchmarkLastIndexAnyASCII(b *testing.B) {
453 x := strings.Repeat("#", 2048) // Never matches set
454 cs := "0123456789abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz"
455 for k := 1; k <= 2048; k <<= 4 {
456 for j := 1; j <= 64; j <<= 1 {
457 b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
458 benchLastIndexAny(b, x[:k], cs[:j])
459 })
460 }
461 }
462 }
463
464 func BenchmarkLastIndexAnyUTF8(b *testing.B) {
465 x := strings.Repeat("#", 2048) // Never matches set
466 cs := "你好世界, hello world. 你好世界, hello world. 你好世界, hello world."
467 for k := 1; k <= 2048; k <<= 4 {
468 for j := 1; j <= 64; j <<= 1 {
469 b.Run(fmt.Sprintf("%d:%d", k, j), func(b *testing.B) {
470 benchLastIndexAny(b, x[:k], cs[:j])
471 })
472 }
473 }
474 }
475
476 func BenchmarkIndexPeriodic(b *testing.B) {
477 key := "aa"
478 for _, skip := range [...]int{2, 4, 8, 16, 32, 64} {
479 b.Run(fmt.Sprintf("IndexPeriodic%d", skip), func(b *testing.B) {
480 s := strings.Repeat("a"+strings.Repeat(" ", skip-1), 1<<16/skip)
481 benchIndex(b, s, key)
482 })
483 }
484 }
485
486 // The below benchmarks are from src/bytes/bytes_test.go
487
488 var bmbuf []byte
489
490 func valName(x int) string {
491 if s := x >> 20; s<<20 == x {
492 return fmt.Sprintf("%dM", s)
493 }
494 if s := x >> 10; s<<10 == x {
495 return fmt.Sprintf("%dK", s)
496 }
497 return fmt.Sprint(x)
498 }
499
500 func benchBytes(b *testing.B, sizes []int, f func(b *testing.B, n int)) {
501 for _, n := range sizes {
502 b.Run(valName(n), func(b *testing.B) {
503 if len(bmbuf) < n {
504 bmbuf = make([]byte, n)
505 }
506 b.SetBytes(int64(n))
507 f(b, n)
508 })
509 }
510 }
511
512 var indexSizes = []int{10, 32, 4 << 10, 4 << 20, 64 << 20}
513
514 func BenchmarkIndexByte_Bytes(b *testing.B) {
515 if *benchStdLib {
516 benchBytes(b, indexSizes, bmIndexByte(strings.IndexByte))
517 } else if *benchLower {
518 fn := func(s string, c byte) int {
519 if 'a' <= c && c <= 'z' {
520 c -= 'a' - 'A'
521 }
522 return strings.IndexByte(strings.ToUpper(s), c)
523 }
524 benchBytes(b, indexSizes, bmIndexByte(fn))
525 } else {
526 benchBytes(b, indexSizes, bmIndexByte(strcase.IndexByte))
527 }
528 }
529
530 func bmIndexByte(index func(string, byte) int) func(b *testing.B, n int) {
531 return func(b *testing.B, n int) {
532 buf := bmbuf[0:n]
533 buf[n-1] = 'x'
534 s := string(buf)
535 for i := 0; i < b.N; i++ {
536 j := index(s, 'x')
537 if j != n-1 {
538 b.Fatal("bad index", j)
539 }
540 }
541 buf[n-1] = '\x00'
542 }
543 }
544
545 func BenchmarkIndexRune_Bytes(b *testing.B) {
546 if *benchStdLib {
547 benchBytes(b, indexSizes, bmIndexRune(strings.IndexRune))
548 } else if *benchLower {
549 fn := func(s string, r rune) int {
550 return strings.IndexRune(strings.ToUpper(s), unicode.ToUpper(r))
551 }
552 benchBytes(b, indexSizes, bmIndexRune(fn))
553 } else {
554 benchBytes(b, indexSizes, bmIndexRune(strcase.IndexRune))
555 }
556 }
557
558 func BenchmarkIndexRuneASCII_Bytes(b *testing.B) {
559 if *benchStdLib {
560 benchBytes(b, indexSizes, bmIndexRuneASCII(strings.IndexRune))
561 } else if *benchLower {
562 fn := func(s string, r rune) int {
563 return strings.IndexRune(strings.ToUpper(s), unicode.ToUpper(r))
564 }
565 benchBytes(b, indexSizes, bmIndexRuneASCII(fn))
566 } else {
567 benchBytes(b, indexSizes, bmIndexRuneASCII(strcase.IndexRune))
568 }
569 }
570
571 func bmIndexRuneASCII(index func(string, rune) int) func(b *testing.B, n int) {
572 return func(b *testing.B, n int) {
573 buf := bmbuf[0:n]
574 buf[n-1] = 'x'
575 s := string(buf)
576 for i := 0; i < b.N; i++ {
577 j := index(s, 'x')
578 if j != n-1 {
579 b.Fatal("bad index", j)
580 }
581 }
582 buf[n-1] = '\x00'
583 }
584 }
585
586 func bmIndexRune(index func(string, rune) int) func(b *testing.B, n int) {
587 return func(b *testing.B, n int) {
588 buf := bmbuf[0:n]
589 utf8.EncodeRune(buf[n-3:], '世')
590 s := string(buf)
591 for i := 0; i < b.N; i++ {
592 j := index(s, '世')
593 if j != n-3 {
594 b.Fatal("bad index", j)
595 }
596 }
597 buf[n-3] = '\x00'
598 buf[n-2] = '\x00'
599 buf[n-1] = '\x00'
600 }
601 }
602
603 // WARN: not part of the stdlib
604 func portableIndexNonASCII(s string) int {
605 for i := 0; i < len(s); i++ {
606 if s[i] >= utf8.RuneSelf {
607 return i
608 }
609 }
610 return -1
611 }
612
613 // WARN: not part of the stdlib
614 func BenchmarkIndexNonASCII_Bytes(b *testing.B) {
615 if testing.Short() {
616 b.Skip("short test")
617 }
618 if *benchLower {
619 b.Skip("skipping: benchmark not relevant with -stdlib-case flag")
620 return
621 }
622 if *benchStdLib {
623 benchBytes(b, indexSizes, bmIndexNonASCII(portableIndexNonASCII))
624 } else {
625 benchBytes(b, indexSizes, bmIndexNonASCII(strcase.IndexNonASCII))
626 }
627 }
628
629 // WARN: not part of the stdlib
630 func bmIndexNonASCII(index func(string) int) func(b *testing.B, n int) {
631 return func(b *testing.B, n int) {
632 buf := bmbuf[0:n]
633 utf8.EncodeRune(buf[n-3:], '世')
634 s := string(buf)
635 for i := 0; i < b.N; i++ {
636 j := index(s)
637 if j != n-3 {
638 b.Fatal("bad index", j)
639 }
640 }
641 buf[n-3] = '\x00'
642 buf[n-2] = '\x00'
643 buf[n-1] = '\x00'
644 }
645 }