Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StreamReader and buffer in C#

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?

like image 913
gravitar Avatar asked Jun 30 '10 09:06

gravitar


2 Answers

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.

like image 164
František Žiačik Avatar answered Oct 06 '22 22:10

František Žiačik


I think this question was already asked somehow differently on stackoverflow: How to write the content of one stream into another stream in .net?

"When using the Read method, it is more efficient to use a buffer that is the same size as the internal buffer of the stream, where the internal buffer is set to your desired block size, and to always read less than the block size. If the size of the internal buffer was unspecified when the stream was constructed, its default size is 4 kilobytes (4096 bytes)."

like image 39
garzanti Avatar answered Oct 06 '22 21:10

garzanti