3 ms·
> This is a pretty surprising behavior. This optimisation crosses the line into "too clever by half". Once a Rust programmers groks how Vec's work their menta
by rstuart4133 3y ago
> This is a pretty surprising behavior.
This optimisation crosses the line into "too clever by half". Once a Rust programmers groks how Vec's work their mental model of how capacity is allocated simple, so simple they hardly need thing about it's implications as they write code. This optimisation breaks that simple model badly, and you would have to be really focused to realise it's about to bite you as the code streams off your finger tips. Consequently this "optimisation" is almost certainly going to cause a lot of code to using far more memory than expected.
You get the same results with filter():
let mut v = vec![1,2,3];
v.push(4);
println!("len {} cap {}", v.len(), v.capacity());
let v = v.into_iter().map(|x| x+1).filter(|_x| false).collect::<Vec<_>>();
println!("len {} cap {}", v.len(), v.capacity());
len 4 cap 6
len 0 cap 6
Despite being in some sense "correct", I'd consider that result a bug. One fix would be to examine the result, and if it breaks the programmers expectations badly (by say using more than twice the memory needed) it does a shink_to_fit() for you. Since the programmer is probably expecting a new vector to be generated it isn't a surprising outcome.