-
Notifications
You must be signed in to change notification settings - Fork 17.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
proposal: strings: add (*Builder).ResetKeepCapacity method #60768
Comments
This seems like a special purpose operation. When does it come up in practice? |
When allocating a bunch of small strings when the total size of all strings in more or less known. func main() {
var b strings.Builder
// Case 1: Size known upfront.
// The size must be known upfront, so that it doesn't grow
// anymore, because it will unecessary reallocate the previous strings
// in the builder.
b.Grow(len("test1") + len("test2"))
str1 := newStringSizeKnown(&b, []byte("test1"))
str2 := newStringSizeKnown(&b, []byte("test2"))
fmt.Println(str1, str2) // test1 test2
b.Reset()
// Case 1: Size not known upfront.
b.Grow(len("test1"))
str1 = newString(&b, []byte("test1"))
str2 = newString(&b, []byte("test2"))
fmt.Println(str1, str2) // test1 test2
}
func newStringSizeKnown(b *strings.Builder, buf []byte) string {
l := b.Len()
b.Write(buf)
return b.String()[l:]
}
func newString(b *strings.Builder, buf []byte) string {
if b.Cap()-b.Len() < len(buf) {
b.Reset()
}
return newStringSizeKnown(b, buf)
} |
Can you explain what this is trying to achieve? What problem does calling |
Just performance optimizations, reduce a bunch of small string allocations into one bigger memory allocation.
With the |
You could keep track of your offsets, call the |
Currently the
strings.Builder
wastes the remaining capacity when(*Builder).Reset
is being called, it works just the same way as creating a new emptystrings.Builder
.Currently it is not possible in a backwards compatibility manner to keep the remaining capacity in the Builder after calling Reset(), because it would require keeping the
b.addr
pointer, so that it is not possible to copy the Builder.I propose adding a simple
(*Builder).ResetKeepCapacity
method with following signature:The text was updated successfully, but these errors were encountered: