Skip to content

Commit 6262192

Browse files
John Potocnyianlancetaylor
authored andcommitted
strings: Add benchmark test for trim function
The strings.Trim function and variants allocate memory on the heap when creating a function to pass into TrimFunc. Add a benchmark to document the behavior; an issue will be submitted to address this behavior in the compiler if possible. Change-Id: I8b66721f077951f7e7b8cf3cf346fac27a9b68c0 Reviewed-on: https://go-review.googlesource.com/8200 Reviewed-by: Ian Lance Taylor <[email protected]>
1 parent c45751e commit 6262192

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

src/strings/strings_test.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -569,6 +569,35 @@ func TestTrim(t *testing.T) {
569569
}
570570
}
571571

572+
func BenchmarkTrim(b *testing.B) {
573+
b.ReportAllocs()
574+
575+
for i := 0; i < b.N; i++ {
576+
for _, tc := range trimTests {
577+
name := tc.f
578+
var f func(string, string) string
579+
switch name {
580+
case "Trim":
581+
f = Trim
582+
case "TrimLeft":
583+
f = TrimLeft
584+
case "TrimRight":
585+
f = TrimRight
586+
case "TrimPrefix":
587+
f = TrimPrefix
588+
case "TrimSuffix":
589+
f = TrimSuffix
590+
default:
591+
b.Errorf("Undefined trim function %s", name)
592+
}
593+
actual := f(tc.in, tc.arg)
594+
if actual != tc.out {
595+
b.Errorf("%s(%q, %q) = %q; want %q", name, tc.in, tc.arg, actual, tc.out)
596+
}
597+
}
598+
}
599+
}
600+
572601
type predicate struct {
573602
f func(rune) bool
574603
name string

0 commit comments

Comments
 (0)