对于 public StreamWriter(Stream stream)构造函数, MSDN 说
初始化StreamWriter的新实例通过使用UTF-8编码和默认的缓冲区大小来指定流的类。
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'回答这里说是 4 KiB(我想是什么意思……KB?),但是没有证实这一点的链接。
I want to use one of the other constructor overloads but would like to use the default buffer size. What is the default buffer size? MSDN does not say anywhere. Rubens Farias' answer here says it's "4 KiB" (whatever that means...KB I guess?) but there's no link to substantiate that.
推荐答案
当文档失败时,请反编译。我总是忘记了!
Ah when documentation fails, decompile. I always forget that!
嗯,不要那样做。不再需要,您可以查看Microsoft程序员编写的实际源代码。总是比反编译代码更好,它带有注释。
Well, don't do that. It isn't necessary anymore, you can look at the actual source code that the Microsoft programmers wrote. Always better than decompiled code, it has comments.
访问参考源网站。它是在一年前更新的,现在它的浏览器界面非常漂亮,实际上比反编译器要快。只需在搜索框中键入StreamWriter。最多需要一秒钟才能发现:
Visit the Reference Source website. It was updated about a fat year ago, it has now a very slick browser interface that's actually faster than a decompiler. Just type StreamWriter in the search box. Takes you at most a dozen seconds to discover:
// 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个字符。而且,如果您写入的是文件而不是流,那么FileStream的缓冲区为4096字节,无法更改。它确实暴露了注释的经典问题,它们有一个不被维护且与代码不匹配的诀窍。实际上并未实施有关自适应缓冲的功能。 KiB是具有1024个脚趾的动物,从来没有1000个脚趾。
So the default is 1024 characters for the StreamWriter. And if you write to a file instead of a stream then there's a FileStream with a 4096 byte buffer, can't change that. It does expose a classic problem with comments, they have a knack for not being maintained and mismatch the code. The noodling about "adaptive buffering" isn't actually implemented. A KiB is an animal with 1024 toes, never 1000.
更多推荐
StreamWriter的默认缓冲区大小是多少
发布评论