作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想回收protobuf的message对象,减少运行时的GC消耗,但不确定是否安全,测试示例代码如下:
测试.proto
message Hello{
uint32 id = 1;
}
测试.pb.go
type Hello struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
ID uint32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
}
func (x *Hello) Reset() {
*x = Hello{}
if protoimpl.UnsafeEnabled {
mi := &file_proto_login_api_login_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
// other codes
主.go
func main() {
// Disable GC to test re-acquire the same data
gc := debug.SetGCPercent(-1)
// As a protobuf object pool
cache := sync.Pool{New: func() interface{} { return &test.Hello{} }}
// Take out an object and use it
m1 := cache.Get().(*test.Hello)
m1.ID = 999
fmt.Println(&m1.ID) // print 999
// Empty the data and put it back into the object pool
m1.Reset()
cache.Put(m1)
// Take out an object again and use it
m2 := cache.Get().(*test.Hello)
fmt.Println(&m2.ID) // print 0
debug.SetGCPercent(gc)
}
最佳答案
您显示的代码是安全的。当对对象的引用在对象被放入池中后被保留时,像这样的池化变得“不安全”。您冒着竞争条件或奇怪错误的风险。因此它还取决于使用您的对象的代码。
据我所知,protocol buffers 库和 gRPC 库不会保留对 protobuf 对象的引用。这样做会破坏很多代码,因为此类库无法知道何时可以安全地重用。
所以只要确保自己的代码在将对象放入池中后不使用对象,就可以了。
关于go - 如何安全地回收 golang 中的 protobuf 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70615855/
我是一名优秀的程序员,十分优秀!