简体   繁体   English

C#中的StreamReader和缓冲区

[英]StreamReader and buffer in C#

I've a question about buffer usage with StreamReader. 我对StreamReader的缓冲区使用有疑问。 Here: http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx you can see: 在这里: http : //msdn.microsoft.com/zh-cn/library/system.io.streamreader.aspx,您可以看到:

"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) . 根据此博客 ,StreamReader的内部缓冲区大小为2k,因此我可以使用Read()避免Read(Char[], Int32, Int32)有效地读取一些kbs的文件。

Moreover, even if a file is big I can construct the StreamReader passing a size for the buffer 而且,即使文件很大,我也可以构造StreamReader并传递缓冲区的大小

So what's the need of an external buffer? 那么,需要外部缓冲区吗?

Looking at the implementation of StreamReader.Read methods, you can see they both call internal ReadBuffer method. 查看StreamReader.Read方法的实现,可以看到它们都调用了内部ReadBuffer方法。

Read() method first reads into internal buffer, then advances on the buffer one by one. Read()方法首先读取内部缓冲区,然后在缓冲区上一步一步前进。

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: Read(char[]...)调用ReadBuffer ,但是调用调用者提供的外部缓冲区:

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. 因此,我认为唯一的性能损失就是您需要比Read(char[])调用Read()多次,并且由于它是一个虚拟方法,因此调用本身会使速度变慢。

I think this question was already asked somehow differently on stackoverflow: How to write the content of one stream into another stream in .net? 我认为这个问题已经在stackoverflow上有所不同: 如何将一个流的内容写入.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)." “使用Read方法时,使用与流内部缓冲区大小相同的缓冲区效率更高,其中内部缓冲区设置为所需的块大小,并且始终读取小于该块大小的缓冲区。如果在构造流时未指定内部缓冲区的大小,则其默认大小为4 KB(4096字节)。”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM