StreamReader and buffer in C#

社会主义新天地 提交于 2021-02-07 12:38:30

问题


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?


回答1:


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.




回答2:


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)."



来源:https://stackoverflow.com/questions/3148131/streamreader-and-buffer-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!