C#中的StreamReader和缓冲区 [英] StreamReader and buffer in C#
问题描述
我对StreamReader的缓冲区使用有疑问.此处: http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx 您可以看到:
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.".
根据此网络日志,StreamReader的内部缓冲区大小为2k,因此我可以使用 Read()
有效地读取一些kbs的文件,而无需 Read(Char [],Int32,Int32)
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并传递缓冲区
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?
推荐答案
看一下 StreamReader.Read
方法的实现,可以看到它们都调用了内部 ReadBuffer
方法
Looking at the implementation of StreamReader.Read
methods, you can see they both call internal ReadBuffer
method.
Read()
方法首先读入内部缓冲区,然后在缓冲区上一个接一个地前进.
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 [] ...)
也会调用 ReadBuffer
,但会调用方提供的外部缓冲区:
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;
}
}
所以我想唯一的性能损失就是您需要调用 Read()
的次数比 Read(char [])
的次数多,并且这是一个虚拟方法,通话本身会降低速度.
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.
这篇关于C#中的StreamReader和缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!