Fasthttp: Performance: SetBody vs SetBodyString

Created on 10 Jan 2020  路  4Comments  路  Source: valyala/fasthttp

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

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 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.

All 4 comments

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:

Was this page helpful?
0 / 5 - 0 ratings

Related issues

shkreios picture shkreios  路  3Comments

imgurbot12 picture imgurbot12  路  5Comments

horgh picture horgh  路  5Comments

jadbox picture jadbox  路  3Comments

facundomedica picture facundomedica  路  4Comments