ceds
ceds

Reputation: 2185

Most Efficient Way to Convert Strings.Builder to Byte Array

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?

Upvotes: 3

Views: 3817

Answers (1)

Thundercat
Thundercat

Reputation: 120979

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.

Upvotes: 5

Related Questions