-
Notifications
You must be signed in to change notification settings - Fork 17.9k
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: bytes: add Buffer.Init #53443
Comments
how is this different from Reset? |
If we get the data and want to wrap it in Buffer, currently we can
|
Can you show an example where this comes up? Thanks. (I think you could actually do this today via b.Reset(buf)
b.Grow(len(buf)) but I'm not sure we want to guarantee that.) |
I am using an encoding library similar to protobuf, the encoder is something like func Encode(Marshaler m) []byte {
bzSize := m.Size()
var buf = bytes.NewBuffer(make([]byte, 0, bzSize))
m.MarshalTo(buf)
return buf.Bytes()
} buf will escape to the heap because of the interface, If sync.Pool is used, a copy is required at the end. func Encode(Marshaler m) (bz []byte) {
bzSize := m.Size()
var buf = pool.Get().(*bytes.Buffer)
buf.Reset()
buf.Grow(bzSize)
m.MarshalTo(buf)
bz = make([]byte, bzSize)
copy(bz, buf.Bytes())
pool.Put(buf)
return
} It is used in performance sensitive scenarios, so I want to reduce allocation or copy |
Perhaps |
@DeedleFake good idea, Buffer already has a |
This doesn't seem like a terribly common operation, and the proposed |
This proposal has been added to the active column of the proposals project |
Based on the discussion above, this proposal seems like a likely decline. |
No change in consensus, so declined. |
This method adds the ability to replace a Buffer's buf.
Currently bytes.NewBuffer can be used to initialize Buffer with a custom buf, or we can copy a custom buf into Buffer via Write, but in performance-sensitive scenarios, I think it would be useful to avoid heap allocation or memcpy. So I want to add a method to replace a Buffer's buf.
a possible implementation:
The text was updated successfully, but these errors were encountered: