Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

cleanup buffer after struct to bytes.Buffer{}

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()
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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()
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading