The default implementation on Stream creates a new single-byte array and then calls Read. While this is formally correct, it is inefficient. Any stream with an internal buffer should override this method and provide a much more efficient version that reads the buffer directly, avoiding the extra array allocation on every call.
Taken from the FileStream.ReadByte documentation:
http://msdn.microsoft.com/en-us/library/system.io.filestream.readbyte.aspx
What is the meaing of this and how do I overcome this inefficiency?
This is only of concern when you inherit from
Stream. When doing so, you must provide at least aReadmethod,ReadByteis implemented on top of it in the base class. This is fine, but inefficient when your stream is capable of getting individual bytes directly – the default implementation would then first create a single-byte buffer internally, pass it toReadByteto fill it, and then return the single byte. If you can implement your buffer so that the single byte can be returned directly, without allocating a temporary buffer, you should do so.For the calling code, the only consideration is that when you need to read bytes just to store them in a buffer,
Readis often more efficient thanReadByte, even when you’re only reading a single byte – but if you really only need one byte, and the stream implementation you’re using provides an optimized version,ReadBytemay actually be faster. If you read individual bytes for immediate processing,ReadByteshouldn’t be a problem at all – after all, most of the standard stream classes are buffered already and should provide an optimizedReadByte. If in doubt, profile.