What would be the best standard to use in terms of high server loads?
I'm having a hard time testing the performance on these methods, @erikdubbelboer could you shine some light on this?
ctx.Response.SetBody([]byte("Hello, World"))
// vs
ctx.Response.SetBodyString("Hello, World")
// vs
ctx.Response.AppendBody([]byte("Hello, World"))
// vs
ctx.Response.AppendBodyString("Hello, World")
// vs
ctx.SetBodyStreamWriter(func(w *bufio.Writer) {
w.Write([]byte("Hello, World"))
w.Flush()
})
It will depend on how you build your body. If you have your body as a []byte or string then SetBody and SetBodyString will be the fastest.
Building your own []byte body and using SetBody can be faster than AppendBody if you reuse the []byte that you build correctly.
SetBodyStreamWriter is more for if you don't want to have the whole response body in memory. With this you can write smaller parts of the response body and flush them to the receiver before you send more.
But SetBody uses SetBodyString in the end
https://github.com/valyala/fasthttp/blob/master/http.go#L611
So ain't it a better standard to always build your body as a string (without conversion if possible) directly and declare
ctx.Response.SetBodyString("Hello, World") as a winner? :smile:
No, since strings in Go are immutable (meaning they can't change) they are almost always slower. Take for example this code: https://play.golang.org/p/GA5GmaNaUb7 here every string generated can't be modified so every iteration a new string is created. While the []byte version just doubles the slice each time it doesn't fit anymore. So building a body part by part using []byte is much much better.
Yes SetBody calls SetBodyString. But it does so with s2b in between which unsafely converts a string to a []byte without an allocation.
@erikdubbelboer Thank you for this explanation, you're doing an amazing job smoothing the learning curve by giving complete answers on all issues :+1: :100: :1st_place_medal:
Most helpful comment
No, since strings in Go are immutable (meaning they can't change) they are almost always slower. Take for example this code: https://play.golang.org/p/GA5GmaNaUb7 here every
stringgenerated can't be modified so every iteration a newstringis created. While the[]byteversion just doubles the slice each time it doesn't fit anymore. So building a body part by part using[]byteis much much better.Yes
SetBodycallsSetBodyString. But it does so withs2bin between which unsafely converts astringto a[]bytewithout an allocation.