trimmer


Summary
trimmer is an alternative implementation of the standard Go strings.Trim, strings.TrimLeft, and strings.TrimRight functions.
Runes to be trimmed away are stored in a bitset for quick retrieval.
On average, trimmer executes at least twice as fast as strings.Trim.
Spot any bugs? Report them here.
Installation
go get github.com/elliotwutingfeng/trimmer
Example
const charsToTrim string = "@ππ½ζ° "
var cutset *intset.Rune = MakeRuneSet(charsToTrim)
fmt.Println(FastTrim("", cutset, TrimBoth))
fmt.Println(strings.Trim("", "@ππ½ζ° "))
fmt.Println(FastTrim(" ", cutset, TrimBoth))
fmt.Println(strings.Trim(" ", "@ππ½ζ° "))
fmt.Println(FastTrim("@bππ½ζ°", cutset, TrimBoth))
fmt.Println(strings.Trim("@bππ½ζ°", "@ππ½ζ° "))
fmt.Println(FastTrim("@bππ½ζ°", cutset, TrimLeft))
fmt.Println(strings.TrimLeft("@bππ½ζ°", "@ππ½ζ° "))
fmt.Println(FastTrim("@bππ½ζ°", cutset, TrimRight))
fmt.Println(strings.TrimRight("@bππ½ζ°", "@ππ½ζ° "))
fmt.Println(FastTrim("@bπζ°", cutset, TrimRight))
fmt.Println(strings.TrimRight("@bπζ°", "@ππ½ζ° "))
//Output:
//
//
//b
//b
//bππ½ζ°
//bππ½ζ°
//@b
//@b
//@b
//@b
Testing
make tests
# Alternatively, run tests without race detection
# Useful for systems that do not support the -race flag like windows/386
# See https://tip.golang.org/src/cmd/dist/test.go
make tests_without_race
Benchmarks
make bench
Results
The following chart indicates total time taken to trim characters @ππ½ζ° from strings in https://github.com/minimaxir/big-list-of-naughty-strings. The strings have been modified to include prefix and/or suffix permutations with replacement of up to length 4 from the set @ππ½ζ°.
CPU: AMD Ryzen 7 5800X
Time in milliseconds (ms) | Lower is better
MakeRuneSet β .08
FastTrim β 252 π¦π¦π¦π¦π¦π¦π¦π¦π¦
FastTrimLeft β 113 π¦π¦π¦π¦
FastTrimRight β 167 π¦π¦π¦π¦π¦π¦
Trim β 680 π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
TrimLeft β 342 π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
TrimRight β 382 π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯π₯
Limitations
The cutset (characters to be trimmed) must be initialized as *intset.Rune first. This incurs a small time cost.
const charsToTrim string = "@ππ½ζ° "
var cutset *intset.Rune = MakeRuneSet(charsToTrim) // this incurs a small time cost
Use the Go Standard library if you only need to process a small amount of strings (10 strings or less) per given cutset. However, for larger amounts of strings per given cutset, trimmer will greatly outperform the standard library.