4 ms·
> a previous version of this blog post did not specify that the New() function should return a pointer type. This avoids an extra allocation when returning thro
by cafxx 7y ago
> a previous version of this blog post did not specify that the New() function should return a pointer type. This avoids an extra allocation when returning through the interface{} type.
While this is good advice, it's not entirely correct. Even with the current go compiler there are ways to use sync.Pool with non-pointer values without incurring in the extra allocation, e.g. using a second sync.Pool to reuse the interface{}. Although I would not recommend it as it's slower, and much less maintainable.
> The safe way to ensure you always zero memory is to do so explicitly:
// reset resets all fields of the AuthenticationResponse before pooling it.
func (a* AuthenticationResponse) reset() {
a.Token = ""
a.UserID = ""
}
I think this is safer, in face of modifications to the AuthenticationResponse structure, and much clearer in its intent:
// reset resets all fields of the AuthenticationResponse before pooling it.
func (a* AuthenticationResponse) reset() {
*a = AuthenticationResponse{}
}