英文:
About the google.golang.org/protobuf why use append not make a had cap slice
问题
// AppendVarint将v作为varint编码的uint64追加到b中。
func AppendVarint(b []byte, v uint64) []byte {
switch {
case v < 1<<7:
b = append(b, byte(v))
case v < 1<<14:
b = append(b,
byte((v>>0)&0x7f|0x80),
byte(v>>7),
// ...
}
return b
}
在需要进行内存复制时使用append
但是我们已经知道了长度
这样做有什么更好的地方吗?
为什么不这样做
switch {
case v < 1<<7:
b = []byte{byte(v)}
case v < 1<<14:
b = []byte{byte((v>>0)&0x7f|0x80), byte(v>>7)}
英文:
// AppendVarint appends v to b as a varint-encoded uint64.
func AppendVarint(b []byte, v uint64) []byte {
switch {
case v < 1<<7:
b = append(b, byte(v))
case v < 1<<14:
b = append(b,
byte((v>>0)&0x7f|0x80),
// ...
}
return b
}
use append while need mem copy
but we had known the length
is this something better?
why not we do like this
switch {
case v < 1<<7:
b = []byte{byte(v)}
case v < 1<<14:
b = []byte{byte((v>>0)&0x7f|0x80), byte(v>>7)}
答案1
得分: 1
append
函数用于向现有切片追加元素,只有在容量不足以容纳额外值时才会重新分配内存。切片字面量始终返回一个唯一的(新分配的)切片。
通常情况下,你使用哪个函数取决于你对切片的具体操作。但在使用protobuf
时,通常是将一个变长编码的整数追加到一个(可能更大)的序列化协议消息中。在这种情况下,使用append
函数具有正确的语义,因为返回一个新的切片可能会进行不必要的内存分配(因为该切片本身只会被追加到包含序列化消息的缓冲区中)。
英文:
append
appends to an existing slice, only reallocating “[i]f the capacity is not large enough to fit the additional values”. A slice literal always returns a unique (newly-allocated) slice.
Which one you use, in general, depends on what you're doing with it, but in the case of protobuf
“what you're doing with it” is generally appending a varint-encoded integer to a (potentially much larger) serialized protocol message. In that case, append
has the right semantics, while returning a new slice would potentially perform an unnecessary allocation (since that slice would itself just be appended onto the buffer containing the serialized message).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论