我有以下代码:
func myfunction() {
results := make([]SomeCustomStruct, 0)
// ... results gets populated ...
for index, value := range results {
results[index].Body = cleanString(value.Body)
}
// ... when done, more things happen ...
}
func cleanString (in string) (out string) {
s := sanitize.HTML(in)
s = strings.Replace(s, "\n", " ", -1)
out = strings.TrimSpace(s)
return
}
切片永远不会包含超过100个条目。有没有什么方法可以在这里利用goroutine来同时对每个切片项执行cleanString函数而不是一个一个?
谢谢!
答案 0 :(得分:3)
如果切片只有100个或更少的项目并且它是cleanString
的全部,那么除非正文字符串相当大,否则你不会获得大量的加速。
将它与goroutines并行化看起来像:
var wg sync.WaitGroup
for index, value := range results {
wg.Add(1)
go func(index int, body string) {
defer wg.Done()
results[index].Body = cleanString(body)
}(index, value.Body)
}
wg.Wait()