以下是使用
strings.Map
生成较少中间数据的解决方案:
strings.Map(func(r rune) rune { if unicode.IsSpace(r) { return -1 } return r },response)
以下是两种功能之间的基准(source data):
BenchmarkSpaceMap 500 2941575 ns/op 221184 B/op 2 allocs/op BenchmarkSpaceFieldsJoin 300 4967475 ns/op 524288 B/op 3 allocs/op
package main_test import ( "strings" "unicode" "testing" ) func SpaceMap(str string) string { return strings.Map(func(r rune) rune { if unicode.IsSpace(r) { return -1 } return r },str) } func SpaceFieldsJoin(str string) string { return strings.Join(strings.Fields(str),"") } func BenchmarkSpaceMap(b *testing.B) { for n := 0; n < b.N; n++ { SpaceMap(data) } } func BenchmarkSpaceFieldsJoin(b *testing.B) { for n := 0; n < b.N; n++ { SpaceFieldsJoin(data) } }