slow building of long string using "+="

95 Views Asked by At

I have very slow http response performance

Used Go and Fasthttp

package main

import (
    "fmt"
    "github.com/valyala/fasthttp"
)

func fastHTTPHandler(ctx *fasthttp.RequestCtx) {
    var s string = ""
    for i := 1; i <= 100000; i++ {
        s += "hello "
    }
    ctx.SetBodyString(s)
}

func main() {
    fmt.Print("Started")
    fasthttp.ListenAndServe(":8081", fastHTTPHandler)
}

And test it in Insomnia (Postman). Time of execution 3-4 sec. Similar code on PHP executed in 900ms.

PHP img

Golang img

1

There are 1 best solutions below

0
On

Using += in just about any language to concatenate large strings is generally going to yield terrible performance, so I wouldn't use that as my metric for anything performance related. That's why most languages have something in their standard library for building large strings. In Java you'd use a java.lang.StringBuilder. In Go, they added strings.Builder a while back. I haven't run it, but I'm fairly confident this will yield much better performance:

s := strings.Builder{}
for i := 1; i <= 100000; i++ {
    s.WriteString("hello ")
}
ctx.SetBodyString(s.String())