StreamReader and buffer in C#

gravitar picture gravitar · Jun 30, 2010 · Viewed 12.5k times · Source

I've a question about buffer usage with StreamReader. Here: http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx you can see:

"When reading from a Stream, it is more efficient to use a buffer that is the same size as the internal buffer of the stream.".

According to this weblog , the internal buffer size of a StreamReader is 2k, so I can efficiently read a file of some kbs using the Read() avoiding the Read(Char[], Int32, Int32).

Moreover, even if a file is big I can construct the StreamReader passing a size for the buffer

So what's the need of an external buffer?

Answer

František Žiačik picture František Žiačik · Jun 30, 2010

Looking at the implementation of StreamReader.Read methods, you can see they both call internal ReadBuffer method.

Read() method first reads into internal buffer, then advances on the buffer one by one.

public override int Read()
{
    if ((this.charPos == this.charLen) && (this.ReadBuffer() == 0))
    {
        return -1;
    }
    int num = this.charBuffer[this.charPos];
    this.charPos++;
    return num;
}

Read(char[]...) calls the ReadBuffer too, but instead into the external buffer provided by caller:

public override int Read([In, Out] char[] buffer, int index, int count)
{
    while (count > 0)
    {
        ...
        num2 = this.ReadBuffer(buffer, index + num, count, out readToUserBuffer);
        ...
        count -= num2;
    }
}

So I guess the only performance loss is that you need to call Read() much more times than Read(char[]) and as it is a virtual method, the calls themselves slow it down.