Will the compiler optimize initialization of a buffer in a loop?

If I write something like this:

fn foo<R: Read>(mut source: R) {
    loop {
        let mut buf = Vec::with_capacity(1024);
        let _ = source.read(&mut buf);
        // ... do something with `buf` ...
    }
}

Will the compiler recognize that it can use the same chunk of memory for each loop iteration or will this allocate new memory each time?

The compiler will most likely allocate each time, since allocation/deallocation is AFAIK a visible side-effect. Allocator, however, will most likely reuse the same block, so it should be fast enough for you to not worry.

1 Like

No: Could the compiler automatically re-use `Box` allocations as an optimization? · Issue #93707 · rust-lang/rust · GitHub

If "do something" is simple enough that the allocator call matters, then you should write

fn foo<R: Read>(mut source: R) {
    let mut buf = Vec::with_capacity(1024);
    loop {
        buf.clear();
        let _ = source.read(&mut buf);
        // ... do something with `buf` ...
    }
}

instead to manually re-use the allocation.

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.