Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
636 views
in Technique[技术] by (71.8m points)

.net - What is the default buffer size for StreamWriter

For the public StreamWriter(Stream stream) constructor, MSDN says

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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;

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...