Can I perform an action on all slice items at once in go?

Issue

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, "\n", " ", -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!

Solution

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()

Answered By – JimB

Answer Checked By – Willingham (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.