I'm using the stringbuilder:
var sb strings.Builder
I need to convert this to []byte to finally send it with bytes.NewBuffer() via http post. I need this to be as quick as possible.
Currently I do it as follows:
var sendText = sb.String()
var byteSend = []byte(sendText)
Is this the best way of doing this?
Use bytes.NewBufferString(sb.String()) if you must start from a strings.Buffer and end with bytes.Buffer. This will incur the cost of a string to []byte conversion (allocation + copy).
There are better alternatives if the problem statement can be relaxed.
If you have control over the code that writes to the strings.Builder, then change the code to write to a bytes.Buffer directly. This is a simple change because bytes.Buffer has all of the strings.Builder methods.
If your goal is to get an io.Reader to use as an HTTP request body, then use strings.NewReader(sb.String()) to get the io.Reader.
These two options do not incur the the cost of the string to []byte conversion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With