Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 401
rory.ap Avatar asked Apr 02 '15 12:04

rory.ap


1 Answers

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.

like image 96
Hans Passant Avatar answered Sep 21 '22 05:09

Hans Passant