C#中缓冲区和流的区别

Difference between Buffer & Stream in C#

我读到 Buffer 是一个字节序列。但我也读到 Stream 也是一个字节序列。那么 Stream 和 Buffer 有什么区别呢?

正如我在评论中所说,缓冲区和流之间的简而言之区别在于,流是从指定源传输信息或向指定源传输信息的序列,而缓冲区是存储在记忆。例如:

FileStream stream = new FileStream("filepath.txt", FileMode.OpenOrCreate);

打开文件流。该流可以被读取、写入或两者兼而有之。由于它不需要任何额外的内存,因此它轻巧且速度快,但任意引用源中的特定数据集可能会很麻烦。 Streams 还受益于连接而不是一组离散的数据,因此您不需要事先知道数据的大小。

反之:

byte[] fileContents = File.ReadAllBytes("filepath.txt");

将文件的所有字节读入内存。当您需要一次操作整个文件,或者为您的程序保留一个“本地副本”以便该文件可以免费用于其他用途时,这很方便。但是,根据源的大小和可用内存量,包含 整个 文件的缓冲区可能不是一个选项。

不过,这只是一个准系统的解释。那里有更彻底的,例如 Marc Gravell puts it:

Many data-structures (lists, collections, etc) act as containers - they hold a set of objects. But not a stream; if a list is a bucket, then a stream is a hose. You can pull data from a stream, or push data into a stream - but normally only once and only in one direction (there are exceptions of course). For example, TCP data over a network is a stream; you can send (or receive) chunks of data, but only in connection with the other computer, and usually only once - you can't rewind the Internet.

Streams can also manipulate data passing through them; compression streams, encryption streams, etc. But again - the underlying metaphor here is a hose of data. A file is also generally accessed (at some level) as a stream; you can access blocks of sequential data. Of course, most file systems also provide random access, so streams do offer things like Seek, Position, Length etc - but not all implementations support such. It has no meaning to seek some streams, or get the length of an open socket.

一个缓冲区有指定的size/length,用于存储数据。另一方面,Stream 用于从一个地方到另一个地方读取和写入信息。例如 FileStream 用于读取和写入文件流本身有一个缓冲区,当填充到其最大大小时缓冲区被刷新并且流中的数据被读取或写入。