tidwall / redcon

Redis compatible server framework for Go
MIT License
2.16k stars 159 forks source link

Request for comment on this line #55

Open rkarthick opened 2 years ago

rkarthick commented 2 years ago

Thank you so much for your work on this tool.

Could you please add a comment to this line? https://github.com/tidwall/redcon/blob/52d396ed1ef10ebff46177d5d2fbc059b3df8227/redcon.go#L28

Is it to ensure buffer cap is bounded? Curious to understand if you have seen an issue in production that triggered this change.

Thanks!

Fusl commented 1 year ago

redcon temporarily buffers all written data in w.b (a []byte, not an actual bytes.Buffer) of the Writer before writing it to the client during a Flush() operation. maxBufferCap is to ensure that if the temporary internal buffer ever grows above 256KiB, memory from this buffer is afterwards released again during a next run of the garbage collector:

// Flush writes all unflushed Write* calls to the underlying writer.
func (w *Writer) Flush() error {
    if w.err != nil {
        return w.err
    }
    _, w.err = w.w.Write(w.b)
    if cap(w.b) > maxBufferCap || w.err != nil {
        w.b = nil // <- frees memory during the next gc run
    } else {
        w.b = w.b[:0] // <- just resets the write cursor/length back to 0 without freeing memory
    }
    return w.err
}