dongli8862 2016-07-26 16:08
浏览 27
已采纳

我可以一次对所有切片项目执行操作吗?

I have the following code:

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, "
", " ", -1)
    out = strings.TrimSpace(s)
    return
}

The slice will never contain more than 100 or so entries. Is there any way I can exploit goroutines here to perform the cleanString function on each slice item at the same time rather than one by one?

Thanks!

  • 写回答

1条回答 默认 最新

  • dongnius85154 2016-07-26 16:20
    关注

    If the slice only has 100 items or less and that's is the entirety of cleanString, you're not going to get a lot of speedup unless the body strings are fairly large.

    Parallelizing it with goroutines would look something like:

    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()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vue3加ant-design-vue无法渲染出页面
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序