`filter` vs `retain`, which is faster and why?

let a = vec![1; 10000000];
let a: Vec<_> = a.into_iter().filter(|&x| x == 1).collect();

let mut a = vec![1; 10000000];
a.retain(|&x| x == 1);

Is this some sort of a homework question? You can easily measure this kind of code yourself using a microbenchmark. However, I'd guess retain here would win because it doesn't need to allocate a new vector and copy each element. But really, measuring is the best if you want to actually compare the performance of two pieces of code.

No, I've already write a bench. But I'm interesting in why I got this result.
After I read the source code I found that there is a DrainFilter behind the retain and it also do some copy.
I still confuse why.

If you have benchmarked, then your question is probably not "which one is faster". For me, as predicted, retain is faster. Again, probably because it needs to do less work as it operates in-place instead of allocating a new array and copying every element.

Just because I want to see some different perspective. :wink:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.