I am using the following to save structs – very many in short time(database read and write). Do I need to clear the buffer or will it be cleaned up right after by garbage collection?
Or should dI use buffer.Reset()
func ToBytes(p interface{}) []byte {
buf := bytes.Buffer{}
enc := gob.NewEncoder(&buf)
err := enc.Encode(p)
if err != nil {
log.Fatal(err)
}
fmt.Println("uncompressed size (bytes): ", len(buf.Bytes()))
return buf.Bytes()
}
>Solution :
buf will be cleaned by the GC, no need to call buf.Reset(). buf.Reset() can be used if you want to reuse buf after you have already used it once.
For example:
package main
import (
"bytes"
"fmt"
)
func main() {
var buf bytes.Buffer
fmt.Fprint(&buf, "Hello")
fmt.Println(buf.String()) // Prints "Hello"
fmt.Fprintln(&buf, " World")
fmt.Println(buf.String()) // Prints "Hello world"
buf.Reset()
fmt.Fprintln(&buf, "Reused!!!")
fmt.Println(buf.String()) // Prints "Reused!!!"
}
I am using the following to save structs – very many in short time(database read and write)
If allocation of buf turns out to be a performance issue, you could reuse buf lifting it to a higher scope and passing it in as variable. For example:
func main() {
var buf bytes.Buffer
for(...) {
...
ToBytes(someVar, &buf)
...
}
}
func ToBytes(p interface{}, buf *bytes.Buffer) []byte {
buf.Reset()
enc := gob.NewEncoder(buf)
err := enc.Encode(p)
if err != nil {
log.Fatal(err)
}
fmt.Println("uncompressed size (bytes): ", len(buf.Bytes()))
return buf.Bytes()
}