From 85a0db545ddf963062260875f2d5961cb9288d8e Mon Sep 17 00:00:00 2001 From: Julien Cretel Date: Fri, 14 Mar 2025 13:24:33 +0100 Subject: [PATCH] strings: add benchmarks for Replace --- src/strings/strings_test.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/strings/strings_test.go b/src/strings/strings_test.go index aa3458c5c9..3f228b703f 100644 --- a/src/strings/strings_test.go +++ b/src/strings/strings_test.go @@ -1473,6 +1473,10 @@ var ReplaceTests = []struct { func TestReplace(t *testing.T) { for _, tt := range ReplaceTests { + allocs := testing.AllocsPerRun(10, func() { Replace(tt.in, tt.old, tt.new, tt.n) }) + if allocs > 1 { + t.Errorf("Replace(%q, %q, %q, %d) allocates %.2f objects", tt.in, tt.old, tt.new, tt.n, allocs) + } if s := Replace(tt.in, tt.old, tt.new, tt.n); s != tt.out { t.Errorf("Replace(%q, %q, %q, %d) = %q, want %q", tt.in, tt.old, tt.new, tt.n, s, tt.out) } @@ -1531,6 +1535,18 @@ func FuzzReplace(f *testing.F) { }) } +func BenchmarkReplace(b *testing.B) { + for _, tt := range ReplaceTests { + desc := fmt.Sprintf("%q %q %q %d", tt.in, tt.old, tt.new, tt.n) + b.Run(desc, func(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + Replace(tt.in, tt.old, tt.new, tt.n) + } + }) + } +} + var TitleTests = []struct { in, out string }{