Question for BufWriter::with_capacity

Compare the following 2 usages of BufWriter:

  1. BufWriter::new(File::create(file)?)
  2. BufWriter::with_capacity(524_288, File::create(file)?)

My question is:

  • Does no.1 usage have risk to spend huge RAM in case a big file such as tens of GB?
  • Does no.2 usage only spend 512k RAM? even file is bigger than 512K bytes.

Please somebody help to make it clear for me. Thanks~

BufWriter::new is equivalent to a BufWriter::with_capacity with some default capacity defined by the standard library, currently 8K but subject to change.

BufWriter will allocate exactly that amount of memory up front and no more.


Thanks @dtolnay , is there any reference document about this default 8K?

Thanks @dtolnay I find it:

pub const DEFAULT_BUF_SIZE: usize = 8 * 1024;
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn new(inner: W) -> BufWriter<W> {
        BufWriter::with_capacity(DEFAULT_BUF_SIZE, inner)