使用 gogo/protobuf 时,如果需要避免为重复字段分配新对象,可以使用固定长度数组。这样可以减少内存分配,提高性能。protobuf 编译器生成的 unmarshal 函数通常会分配新对象并附加到切片,但通过重用现有内存并避免同时分配,可以实现优化。
考虑一个简单的 protobuf 文件:
syntax = "proto3";
package tutorial;
import "github.com/gogo/[email protected]/gogoproto/gogo.proto";
message point {
uint32 timestamp = 1;
double value = 2;
}
message metric {
string metric = 1;
repeated point points = 2 [(gogoproto.nullable) = false];
}
我已经使用 https://github.com/gogo/protobuf 将 proto 编译为 go
gogoproto.nullable 帮助生成 point 切片作为非指针(指针将使垃圾收集器工作更多):
type metric struct {
metric string `protobuf:"bytes,1,opt,name=metric,proto3" json:"metric,omitempty"`
points []point `protobuf:"bytes,2,rep,name=points,proto3" json:"points"`
xxx_nounkeyedliteral struct{} `json:"-"`
xxx_unrecognized []byte `json:"-"`
xxx_sizecache int32 `json:"-"`
}
但是生成的 unmarshal 函数始终分配新对象并附加到切片。
m.Points = append(m.Points, Point{})
这些小分配很繁重并且会影响性能。我想重用相同的内存并避免一起分配,也许使用固定长度的数组?这可以做到吗?如何做到?
正确答案
m.Points = append(m.Points, Point{})
此代码中没有堆分配(假设 m.points 有足够的容量)。 point{} 在堆栈上分配一个对象,并按值将其复制到切片中。
终于介绍完啦!小伙伴们,这篇关于《使用gogo/protobuf时避免给重复字段分配新对象》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!
本文内容来源于互联网,如有侵权请联系删除。
