是否必须在sync.Pool New函数中返回指针类型?

问题描述:

I saw the issue on Github which says sync.Pool should be used only with pointer types, for example:

var TPool = sync.Pool{
    New: func() interface{} {
       return new(T)
    },
}

Does it make sense? What about return T{} and which is the better choice, why?

我看到了问题说同步。应该仅对指针类型使用 strong>池,例如: p>

  var TPool = sync.Pool {
新功能:func()接口{} {
返回new(T)
},
} 
  code>  pre> 
 
 

是否有意义? 那么 return T {} code>呢?哪个是更好的选择,为什么呢? p> div>

The whole point of sync.Pool is to avoid (expensive) allocations. Large-ish buffers, etc. You allocate a few buffers and they stay in memory, available for reuse. Hence the use of pointers.

But here you'll be copying the values on every step, defeating the purpose. (Assuming your T is a "normal" struct and not something like SliceHeader)

It is not necessary. In most cases it should be a pointer as you want to share an object, not to make copies.

In some use cases this can be a non pointer type, like an id of some external resource. I can imagine a pool of paths (mounted disk drives) represented with strings where some large file operations are being conducted.