C# 中的 StreamReader 和缓冲区
我对 StreamReader 的缓冲区使用有疑问。 此处:http://msdn.microsoft.com/en-us /library/system.io.streamreader.aspx 可以看到:
“从流读取时,使用与流的内部缓冲区大小相同的缓冲区会更有效。”。
根据这个 weblog ,内部缓冲区大小StreamReader 的大小为 2k,因此我可以使用 Read()
有效地读取一些 kbs 的文件,避免使用 Read(Char[], Int32, Int32)
。
此外,即使文件很大,我也可以构造 StreamReader 传递 buffer
那么为什么需要外部缓冲区呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看 StreamReader.Read 方法的实现,您可以看到它们都调用内部的 ReadBuffer 方法。
Read()
方法首先读入内部缓冲区,然后逐个读取缓冲区。Read(char[]...)
也调用ReadBuffer
,而是调用调用者提供的外部缓冲区:所以我想唯一的性能损失是你需要调用
Read()
的次数比Read(char[])
的次数多得多,并且由于它是虚拟方法,调用本身会减慢速度。Looking at the implementation of
StreamReader.Read
methods, you can see they both call internalReadBuffer
method.Read()
method first reads into internal buffer, then advances on the buffer one by one.Read(char[]...)
calls theReadBuffer
too, but instead into the external buffer provided by caller:So I guess the only performance loss is that you need to call
Read()
much more times thanRead(char[])
and as it is a virtual method, the calls themselves slow it down.我认为这个问题已经在 stackoverflow 上以不同的方式提出: .net中如何将一个流的内容写入另一个流?
“使用Read方法时,使用与内部缓冲区大小相同的缓冲区会更有效流,其中内部缓冲区设置为所需的块大小,并且始终读取小于块大小的数据。如果在构造流时未指定内部缓冲区的大小,则其默认大小为 4 KB(4096 字节)。 ”。
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)."