1

I found String's "+" operation is so slowly on Go:

func main() {
    start := time.Now();
    s := ""
    for i:=0;i<100000;i++ {
        s += "test"
    }
    end := time.Now();
    fmt.Println(end.Sub(start))    //Output 6.495225211s
}

But Python:

start = datetime.now()

s = ""

for i in range(100000):
    s += 'test'

end = datetime.now()

print(end - start)    # Output 0:00:00.020291

I know how to optimize the Go code. I hope you can tell me why.

thanks.


I found a interesting thing on Python:

s = ""
for i in range(20):
    s += 'test'
    print(id(s))

the output is:

139842066321960

139842066396912

139842066396912

139842066400072

139842066400072

139842067023232

139842067023232

139842066384304

139842066384304

139842066312528

Community
  • 1
  • 1
LWH
  • 97
  • 3
  • 11
  • 4
    Python has optimised `+=`, avoiding creating a new string object each time; this was done because it is a common error to use `+=` to concatenate strings in a loop. You shouldn't use `+=` if you can avoid it however, use `str.join()` or just `'test' * 100000`. – Martijn Pieters Oct 01 '16 at 13:37
  • 2
    See [Why is variable1 += variable2 much faster than variable1 = variable1 + variable2](https://stackoverflow.com/q/25503703) – Martijn Pieters Oct 01 '16 at 13:39
  • Presumably go is creating new string objects for each concatenation too. Perhaps go has a string concatenation method that can join multiple strings into one in one step? – Martijn Pieters Oct 01 '16 at 13:41
  • 3
    Related / possible duplicate of [How to efficiently concatenate strings in Go?](http://stackoverflow.com/questions/1760757/how-to-efficiently-concatenate-strings-in-go) – icza Oct 01 '16 at 14:01

0 Answers0