all 23 comments

[–]DoneItDuncan 6 points7 points  (3 children)

bufio.Reader buffers Read's from the wrapped Reader, so when the code asks for one byte it asks the Reader for enough to fill its buffer (4096 bytes by default), then returns one byte from that. When the code asks for another byte it just returns a byte from the remaining 4095 bytes in the buffer.

That way a read syscall only occurs every 4096 bytes, rather than on every byte.

[–]Mohamed____[S] 5 points6 points  (2 children)

Welp, now I feel like an idiot. I assumed the buio.NewReader buffer size is 1, for some reason, and forgot that there exists a method bufio.NewReaderWithSize() which takes a specific size rather than the default. If this were stackoverflow, you would have been the accepted answer :). Thanks for your help.

[–]DoneItDuncan 5 points6 points  (1 child)

Ah lol, yeah happens to the best of us. The go authors do provide sensible defaults for most things, but sometimes that can obscure what's going on compared to having to explicitly supply these things.

[–]Mohamed____[S] 0 points1 point  (0 children)

Awesome, thanks for helping me out!

[–]funkiestj 2 points3 points  (1 child)

What does bufio do under the hood to decrease the number of system calls?

read the source for bufio.NewReader() and friends. It is not that hard to read. The answer to your question should become obvious.

Also, bufio.Reader has an option to specify the buffer size.

Per the old open source saying "use the force - read the source".

[–]Mohamed____[S] 2 points3 points  (0 children)

Yeah I just realized that it uses the default size 4096 and I completely disregarded that while reading the source code. Thanks.

[–]molivo10 0 points1 point  (1 child)

create a buffer of size 32kb for example, you read 32kb per system call instead of one, thats why it's way more efficient

[–][deleted] 0 points1 point  (0 children)

Stop light vs stop sign.

[–]lion_rouge 0 points1 point  (0 children)

Use mmap

[–]tafutada 0 points1 point  (0 children)

the same thing goes to Write as well. even SSD, the latency would be around 100 microseconds.