9

In Java and C# there are several classes for buffering streams: BufferedStream in C#, Buffered(Input|Output)Stream and Buffered(Reader|Writer).

They gets some stream in constructor and implements the same interface.

The question is - how it works?

What happens, when I'm trying to read one byte? It reads a lot of bytes into inner buffer and then returns it to me byte after byte? On writing one byte? Writes into inner buffer and on flush() writes it to inner stream?

And about reading/writing an array of bytes - is it inefficient to do it on buffered streams cause of double copying bytes into and from inner array?

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
VorobeY1326
  • 782
  • 10
  • 25

1 Answers1

3

It reads a lot of bytes into inner buffer and then returns it to me byte after byte?

Basically, yes. It takes time to request data from disk platters or from a TCP stream, so it can be more efficient to get a whole chunk of bytes at once, rather than trying to retrieve them individually from the source.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
  • So, buffered stream is useful if I'm reading a lot of bytes and want to read them byte after byte, not thinking about reading into buffer? And is useless if I want to read an array of bytes manually into my buffer? – VorobeY1326 May 17 '13 at 15:41
  • 2
    Buffered stream is useful if your data source has some request overhead, and you want to limit the number of requests. A hard drive takes about 1/120 of a second to completely rotate around, so if you retrieve 120 characters from it character-by-character, in the worst case it could take a whole second. But if you retrieve all 120 characters at once, you can do it in a single rotation. Sure, you can create your own buffer, but why reinvent the wheel? – Robert Harvey May 17 '13 at 15:45
  • 2
    Note that a FileStream in .NET is already sufficiently buffered to use with a hard disk. You only need `BufferedStream` if you're reading TCP packets from a socket, or something like that. – Robert Harvey May 17 '13 at 15:47
  • Just to be clear though: This is a transient buffer and isn't actually capturing the stream. – Christian Bongiorno May 17 '13 at 18:56