c# - C# 中的 StreamReader 和缓冲区

标签 c# streaming buffer streamreader buffering

我对 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/

相关文章:

c# - 我应该如何本地化静态 ComboBox 项目?

c# - RegEx 帮助 - 从 JavaScript 转换为 C#

python - Python 中的 Hadoop 流作业失败(不成功)

streaming - API v2 的实时流缩略图有一半时间无效

java - Twitter4j v2.2.6 具有地理定位功能的流媒体 API

c++ - vector 缓冲区的 vector c++

c# - 使用正则表达式在字符串中查找以某个索引开头的索引

c# - 如何更改 ViewCell 中的高度

c - c中的缓冲区溢出和将局部变量压入堆栈的顺序

node.js - 如何将 base64 字符串格式的图像转换为 sharp image downsizer 期望的数据类型?