-
Notifications
You must be signed in to change notification settings - Fork 18.8k
Description
Proposal Details
There is currently no support for appending the result of any of the string transformation functions1 (Join, Replace(All)?, Repeat, Map, To(Title|Upper|Lower)(Special)?, ToValidUtf8) directly to a Builder, bypassing the intermediate temporary allocation:
// var b strings.Builder (assume that the backing buffer has been preallocated)
s := strings.Repeat(...) // intermediate temporary allocation
b.WriteString(s) // s dead hereThe necessary presence of that temporary allocation partially defeats the purpose of Builder. I most recently ran into this while building SQL queries with varying number of placeholders (Repeat) and columns (Join).
Any of the following would address this issue, with different tradeoffs:
- somehow ensure that the compiler is able to elide that intermediate temporary allocation
- add variants of the transformation functions1 that target either a
Builder(or more in general aio.Writer, but in this case we will still want to add special handling for the case in which theio.Writeris aBuilder) -- e.g. for functionFoo(...) stringwe would get something likeAppendFoo(*Builder, ...) intorAppendFoo(io.Writer, ...) (int, error)2 - add a wrapper type in package strings that can be used to add all these string transformation methods1 to an existing
io.Writer(again, with the case of theio.Writerbeing aBuilderbeing handled specially) -- e.g. for functionFoo(...) stringwe would get something likeWriteWapper(io.Writer).Foo(...) (int, error)2
Option 1 would be possibly the best from a user perspective, as it would transparently apply to existing code and would not require new APIs (nor a full-blown proposal), but seems a bit tricky as it would involve teaching the compiler about some of these functions/types and/or significantly strengthening escape analysis.
Option 2 and 3 could be useful beyond strings.Builder, but they require duplicating a number of existing APIs.
Footnotes
-
internally most of these strings transformation methods already instantiate an ephemeral
Builderto accumulate the result of their work, so the existing methods could likely share their implementation with the ones being proposed ↩ ↩2 ↩3 -
the proposed names,
AppendFooandWriteWrapper, are currently just placeholders... suggestions welcome ↩ ↩2
Metadata
Metadata
Assignees
Labels
Type
Projects
Status