-
Notifications
You must be signed in to change notification settings - Fork 18.8k
Closed
Labels
Milestone
Description
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() intIn 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%Reactions are currently unavailable