我对 StreamReader 的缓冲区使用有疑问。 这里:http://msdn.microsoft.com/en-us/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.".
根据这个weblog ,StreamReader 的内部缓冲区大小为 2k,因此我可以使用 Read()
有效地读取一些 kbs 的文件,避免 Read(Char[], Int32, Int32)
.
此外,即使文件很大,我也可以构造 StreamReader,传递 buffer 的大小。
那么外部缓冲区有什么用呢?
最佳答案
查看 StreamReader.Read
方法的实现,您可以看到它们都调用了内部的 ReadBuffer
方法。
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[]...)
也会调用 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;
}
}
所以我想唯一的性能损失是你需要调用 Read()
的次数比 Read(char[])
多得多,因为它是一个虚拟方法,调用本身会减慢速度。
关于c# - C# 中的 StreamReader 和缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3148131/