4

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?

2
  • 2
    What about bytes.NewBufferString(sb.String())? Commented Mar 27, 2021 at 19:14
  • That's a good suggestion. Will have to do a benchmark to test if it will make a difference Commented Mar 27, 2021 at 19:15

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.