Discussion on: How to Add Buffering to a Reader / Writer in Zig

btree profile image
btree • Edited on

Thanks, Loris.
I wonder what are the scenarios for using buffered writer / reader. Looks like it shouldn't be always recommended. E.g., when the underlying Writer / Reader already provide a buffer argument at creation time [1], it seems there is 0 performance gain by wrapper a buffered writer / reader on top of it. In fact, it adds additional memory copy which slows things down. Is my understanding correct? Thanks.

[1] github.com/fengb/zig-https-example...

kristoff profile image
Loris Cro Author

If the underlying stream is already buffered then of course adding more buffering will not improve things. One practical example that I've encountered today where buffering made a big difference is when serializing a struct into JSON.

I'm working on a piece of the Zig compiler that reads source code and automatically generates docs from it. The job mostly consists in collecting type information an then serializing it into a JSON file. The original code serialized (using std.json) directly into a File.Writer and took about 10s to do the job when run on the Zig standard library. After the change the serialization step took less than 1 second.