StreamWriter 的默认缓冲区大小是多少

What is the default buffer size for StreamWriter

对于 public StreamWriter(Stream stream) 构造函数,MSDN 表示

Initializes a new instance of the StreamWriter class for the specified stream by using UTF-8 encoding and the default buffer size.

我想使用其他构造函数重载之一,但想使用默认缓冲区大小。默认缓冲区大小是多少? MSDN 没有说任何地方。 Rubens Farias' answer here 说它是“4 KiB”(不管那是什么意思……我猜是 KB?)但是没有 link 来证实这一点。

Ah when documentation fails, decompile. I always forget that!

好吧,别那样做。已经没有必要了,你可以看看微软程序员写的实际源代码。总是比反编译代码好,有注释

访问 Reference Source 网站。它大约在一年前更新,现在它有一个非常漂亮的浏览器界面,实际上比反编译器更快。只需在搜索框中键入 StreamWriter。最多花你十几秒来发现:

    // For UTF-8, the values of 1K for the default buffer size and 4K for the
    // file stream buffer size are reasonable & give very reasonable
    // performance for in terms of construction time for the StreamWriter and
    // write perf.  Note that for UTF-8, we end up allocating a 4K byte buffer,
    // which means we take advantage of adaptive buffering code.
    // The performance using UnicodeEncoding is acceptable.  
    internal const int DefaultBufferSize = 1024;   // char[]
    private const int DefaultFileStreamBufferSize = 4096;

因此 StreamWriter 默认为 1024 个字符。如果你写入一个文件而不是一个流,那么有一个带有 4096 字节缓冲区的 FileStream,不能改变它。它确实暴露了一个经典的注释问题,它们有一个不被维护和与代码不匹配的诀窍。关于 "adaptive buffering" 的闲聊实际上并没有实现。 KiB 是一种有 1024 个脚趾的动物,而不是 1000 个。