Isn't filter + map always slower than a single iteration for loop?

105 points PeterParkedPlenty

I am starting to learn about Rust. One thing that seems to be very popular are iterators and the .map and .filter methods.

Don't get me wrong, I am big fan of those! I used them all the time in Lisp and they are very ergonomic. However, I have this feeling that they are inherently less efficient than a for loop.

For example, let's say I have a list of numbers and I want to get all the numbers higher than 30 and add 10 to them.

With filter + map (pseudocode):

v
  .filter(|&x| {x > 30 })
  .map( |x| {x + 10})

However, in this case, it seems to me that some elements (notably those over 30) are being processed twice:

  1. First they are processed by the filter, which "leaves them be"
  2. Second, they are processed by the map, which applies the function

Using a standard for loop, I would do:

for elem in v {
   if elem > 30: continue
   elem += 10;
}

In this case, each element is only processed once.

Am I missing something here? Or is my intuition correct?