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

ror*_*.ap 26 .net streamwriter

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

使用UTF-8编码和默认缓冲区大小为指定的流初始化StreamWriter类的新实例.

我想使用其他构造函数重载之一,但想使用默认的缓冲区大小.什么是默认缓冲区大小?MSDN没有说任何地方. 鲁本斯法里亚斯的答案在这里说它是"4 KiB"(无论那意味着...... KB我猜?)但是没有任何证据可以证实这一点.

Han*_*ant 43

当文档失败时,反编译.我总是忘记那个!

好吧,不要那样做.不再需要了,您可以查看Microsoft程序员编写的实际源代码.总是比反编译代码好,它有评论.

访问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;
Run Code Online (Sandbox Code Playgroud)

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