Skip to content

proposal: strings: add Builder.Available and Builder.AvailableBuffer #62209

Description

@korzhao

I propose adding functions Builder.Available and Builder.AvailableBuffer.

// AvailableBuffer returns an empty buffer with b.Available() capacity.
func (b *Builder) AvailableBuffer() []byte

// Available returns how many bytes are unused in the buffer.
func (b *Builder) Available() int

In recent years, we have added many append-like APIs. It would be great if strings.Builder could benefit from it.

One scenario I can think of is base64 encoding:

For example:

// EncodeToString returns the base64 encoding of src.
func (enc *Encoding) EncodeToString(src []byte) string {
	build := strings.Builder{}
	build.Grow(enc.EncodedLen(len(src)))

	buf := build.AvailableBuffer()
	buf = enc.AppendEncode(buf, src)

	build.Write(buf)
	return build.String()
}

Bench:

benchmark                      old ns/op     new ns/op     delta
BenchmarkEncodeToString-10     6115          4999          -18.25%

benchmark                      old MB/s     new MB/s     speedup
BenchmarkEncodeToString-10     1339.73      1638.63      1.22x

benchmark                      old allocs     new allocs     delta
BenchmarkEncodeToString-10     2              1              -50.00%

benchmark                      old bytes     new bytes     delta
BenchmarkEncodeToString-10     24576         12288         -50.00%

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions