0
\$\begingroup\$

I'm learning string algorithms and I wanted to optimize the basic suffix algorithm which I implemented.

suffix.go

package main

import (
  "fmt"
)

func main(){
  str := "Hello"
  arr := []string{}
  for i:=len(str)-1; i >=0 ; i--{
    var s string
    s = s+str[i:]
    fmt.Println(s)
    arr = append(arr, s)
  }
}

The problem with the above code is, every time I'm creating a new string. I'm trying to avoid it but was not able to do.

\$\endgroup\$
3
\$\begingroup\$

There is no need to create a new string at each iteration. You can directly append the subslice to the array like this:

arr = append(arr, str[i:])

An other easy optimisation would be to create an array with the correct capacity to save an allocation at each iteration, as we know that arr will have the same length as str:

arr := make([]string, len(str))

so the code can now be rewritten like this:

func new() {
    str := "Hello"

    arr := make([]string, 0, len(str))
    for i := len(str) - 1; i >= 0; i-- {
        arr = append(arr, str[i:])
    }
}

Running a small benchmark comparing the old and the new implementation, we get this result:

goos: linux
goarch: amd64
BenchmarkOld-2           3000000               553 ns/op             240 B/op          4 allocs/op
BenchmarkNew-2          10000000               127 ns/op              80 B/op          1 allocs/op
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.