在Go中使用缓冲区进行读取和读取操作示例

my os background is not strong, could someone provide some examples (in Go please if possible), why using buffer is important?

Assuming you're talking about IO:

Imagine you have a var fin *os.File and that file wrapped in a buffer, var instrm *bufio.Reader. Now imagine you are writing some kind of parser that reads the input one character (lets say byte) at a time. Package bufio implements buffered I/O.

If you call myParser.Parse(fin) you will call .Read 4,194,304 times to read each byte, which will make a system call 4,194,304 times, which will cause 4,194,304 context switches. context switches are when control transfers from the userspace program to the OS and are one of the slowest (non-IO) operations. In situations where the OS is not coalescing/prefetching IO requests there is also the horrible possibility your IO device is seeking and reading one byte at a time, but most operating system's IO elevator, prefetching and device-side buffers prevent this nowadays (but it is always better to read in large sequential batches).

If you call myParser.Parse(instrm) with the default bufio.Reader buffer being 4K you will cause 1,024 context switches (each system call reads 4K rather than 1 byte). Since each system call has some overhead, this will mean less time is spent making system calls and more time for your program to run. It is also worth pointing out that running this way (without the extra context switches) will often increase the CPU instruction cache hit rate since more time will be spent branching within a smaller region of memory.

Buffers are even important in areas like network IO as it will allow you to send bursts of packets at the maximum MTU size rather than sending a trickle of tiny packets.

Just don't forget to flush your write buffers.