About the google.golang.org/protobuf why use append not make a had cap slice

huangapple go评论82阅读模式
英文:

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 &lt; 1&lt;&lt;7:
		b = append(b, byte(v))
	case v &lt; 1&lt;&lt;14:
		b = append(b,
			byte((v&gt;&gt;0)&amp;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 &lt; 1&lt;&lt;7:
		b = []byte{byte(v)}
	case v &lt; 1&lt;&lt;14:
		b = []byte{byte((v&gt;&gt;0)&amp;0x7f|0x80), byte(v&gt;&gt;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).

huangapple
  • 本文由 发表于 2021年7月26日 15:41:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/68526131.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定