From 85d770d34020ba6ded937ad15aa629f52517c415 Mon Sep 17 00:00:00 2001 From: Name <1911860538@qq.com> Date: Sun, 22 Mar 2026 11:04:12 +0800 Subject: [PATCH] perf(core/stringx): replace manual char filter with strings.Map (#5453) Co-authored-by: 1911860538 --- core/stringx/strings.go | 21 ++++++++------------- core/stringx/strings_test.go | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+), 13 deletions(-) diff --git a/core/stringx/strings.go b/core/stringx/strings.go index 5a9554a7b..dadf2c52c 100644 --- a/core/stringx/strings.go +++ b/core/stringx/strings.go @@ -3,6 +3,7 @@ package stringx import ( "errors" "slices" + "strings" "unicode" "github.com/zeromicro/go-zero/core/lang" @@ -21,20 +22,14 @@ func Contains(list []string, str string) bool { return slices.Contains(list, str) } -// Filter filters chars from s with given filter function. -func Filter(s string, filter func(r rune) bool) string { - var n int - chars := []rune(s) - for i, x := range chars { - if n < i { - chars[n] = x +// Filter filters chars from s with given remove function. +func Filter(s string, remove func(r rune) bool) string { + return strings.Map(func(r rune) rune { + if remove(r) { + return -1 } - if !filter(x) { - n++ - } - } - - return string(chars[:n]) + return r + }, s) } // FirstN returns first n runes from s. diff --git a/core/stringx/strings_test.go b/core/stringx/strings_test.go index 3fb3e7bce..b4681fe5c 100644 --- a/core/stringx/strings_test.go +++ b/core/stringx/strings_test.go @@ -92,6 +92,24 @@ func TestFilter(t *testing.T) { } } +func BenchmarkFilter(b *testing.B) { + b.Run("true", func(b *testing.B) { + b.ResetTimer() + b.ReportAllocs() + for i := 0; i < b.N; i++ { + Filter(`ab,cd,ef`, func(r rune) bool { return r == ',' }) + } + }) + + b.Run("false", func(b *testing.B) { + b.ResetTimer() + b.ReportAllocs() + for i := 0; i < b.N; i++ { + Filter(`ab,cd,ef`, func(r rune) bool { return r == '!' }) + } + }) +} + func TestFirstN(t *testing.T) { tests := []struct { name string