Skip to content

Commit 0257ee2

Browse files
1911860538kevwan
authored andcommitted
perf(core/stringx): replace manual char filter with strings.Map
1 parent ec802e2 commit 0257ee2

File tree

2 files changed

+26
-13
lines changed

2 files changed

+26
-13
lines changed

core/stringx/strings.go

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package stringx
33
import (
44
"errors"
55
"slices"
6+
"strings"
67
"unicode"
78

89
"github.com/zeromicro/go-zero/core/lang"
@@ -21,20 +22,14 @@ func Contains(list []string, str string) bool {
2122
return slices.Contains(list, str)
2223
}
2324

24-
// Filter filters chars from s with given filter function.
25-
func Filter(s string, filter func(r rune) bool) string {
26-
var n int
27-
chars := []rune(s)
28-
for i, x := range chars {
29-
if n < i {
30-
chars[n] = x
25+
// Filter filters chars from s with given remove function.
26+
func Filter(s string, remove func(r rune) bool) string {
27+
return strings.Map(func(r rune) rune {
28+
if remove(r) {
29+
return -1
3130
}
32-
if !filter(x) {
33-
n++
34-
}
35-
}
36-
37-
return string(chars[:n])
31+
return r
32+
}, s)
3833
}
3934

4035
// FirstN returns first n runes from s.

core/stringx/strings_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,24 @@ func TestFilter(t *testing.T) {
9292
}
9393
}
9494

95+
func BenchmarkFilter(b *testing.B) {
96+
b.Run("true", func(b *testing.B) {
97+
b.ResetTimer()
98+
b.ReportAllocs()
99+
for i := 0; i < b.N; i++ {
100+
Filter(`ab,cd,ef`, func(r rune) bool { return r == ',' })
101+
}
102+
})
103+
104+
b.Run("false", func(b *testing.B) {
105+
b.ResetTimer()
106+
b.ReportAllocs()
107+
for i := 0; i < b.N; i++ {
108+
Filter(`ab,cd,ef`, func(r rune) bool { return r == '!' })
109+
}
110+
})
111+
}
112+
95113
func TestFirstN(t *testing.T) {
96114
tests := []struct {
97115
name string

0 commit comments

Comments
 (0)