- Hands-On System Programming with Go
- Alex Guerrieri
- 196字
- 2021-06-24 13:42:27
Efficient writing
Each time the os.File method, that is, Write, is executed, this translates to a system call, which is an operation that comes with some overhead. Generally speaking, it's a good idea, to minimize the number of operations by writing more data at once, thus reducing the time that's spent on such calls.
The bufio.Writer struct is a writer that wraps another writer, like os.File, and executes write operations only when the buffer is full. This makes it possible to execute a forced write with the Flush method, which is generally reserved until the end of the writing process. A good pattern of using a buffer would be the following:
var w io.WriteCloser
// initialise writer
defer w.Close()
b := bufio.NewWriter(w)
defer b.Flush()
// write operations
defer statements are executed in reverse order before returning the current function, so the first Flush ensures that whatever is still on the buffer gets written, and then Close actually closes the file. If the two operations were executed in reverse order, flush would have tried to write a closed file, returning an error, and failed to write the last chunk of information.