Re:Identifying Rust's collect:<Vec<_>>() memory leak footgun
by tsnl on Thursday January 18, 2024 @01:53PM
(#39045971)
Another downside of Box<T> is that Vec::into_boxed_slice copies all elements from the source vector. Vec::shrink_to_fit does not appear to copy.
This is based on the stable docs.
[ Parent
| on HN ]
Re:Identifying Rust's collect:<Vec<_>>() memory leak footgun
by sapiogram on Thursday January 18, 2024 @02:02PM
(#39046082)
It doesn't copy the elements if the source vector is already at max capacity, which you can often arrange for beforehand.
Re:Identifying Rust's collect:<Vec<_>>() memory leak footgun
by cmrx64 on Thursday January 18, 2024 @02:14PM
(#39046232)
For example, by explicitly calling shrink_to_fit. So you either have fragmentation, or an extra copy if you're not careful, but none of the solutions let you forget about the detail entirely.
Re:Identifying Rust's collect:<Vec<_>>() memory leak footgun
by invpt on Thursday January 18, 2024 @02:34PM
(#39046488)
If you look at the source for into_boxed_slice, it calls shrink_to_fit at the beginning before doing anything else. Hence the documentation is slightly wrong, and no copies occur.
Edit: I submitted a PR to clear up the docs: https://github.com/rust-lang/rust/pull/120110