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 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应