perf(core/stringx): replace manual char filter with strings.Map (#5453)

Co-authored-by: 1911860538 <alxps1911@gmail.com>
This commit is contained in:
Name
2026-03-22 11:04:12 +08:00
committed by GitHub
parent 8cd7f7a2d8
commit 85d770d340
2 changed files with 26 additions and 13 deletions

View File

@@ -3,6 +3,7 @@ package stringx
import ( import (
"errors" "errors"
"slices" "slices"
"strings"
"unicode" "unicode"
"github.com/zeromicro/go-zero/core/lang" "github.com/zeromicro/go-zero/core/lang"
@@ -21,20 +22,14 @@ func Contains(list []string, str string) bool {
return slices.Contains(list, str) return slices.Contains(list, str)
} }
// Filter filters chars from s with given filter function. // Filter filters chars from s with given remove function.
func Filter(s string, filter func(r rune) bool) string { func Filter(s string, remove func(r rune) bool) string {
var n int return strings.Map(func(r rune) rune {
chars := []rune(s) if remove(r) {
for i, x := range chars { return -1
if n < i {
chars[n] = x
} }
if !filter(x) { return r
n++ }, s)
}
}
return string(chars[:n])
} }
// FirstN returns first n runes from s. // FirstN returns first n runes from s.

View File

@@ -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) { func TestFirstN(t *testing.T) {
tests := []struct { tests := []struct {
name string name string