Search code examples
rust

For vector values, which is faster, for loop or for_each?


I'm trying to insert each item in a vector into a map. Which one is preferred and faster, using a for-loop or an iterator via for_each?

  • for-loop

    for api_config in apis {
        insert(api_config);
    }
    
  • for_each

    apis.into_iter().for_each(|api_config| insert(api_config));
    

Solution

  • The official documentation states that for and for_each have the same runtime performance:

    "The implementations of closures and iterators are such that runtime performance is not affected. This is part of Rust’s goal to strive to provide zero-cost abstractions."

    ~ https://doc.rust-lang.org/book/ch13-04-performance.html

    If you are unsure which of two different implementations is faster (no matter if its about for loops or not) you can always measure it yourself. When doing so make sure to use big arrays (maybe with a size of >100k) so that your measurements will be more accurate.

    use std::time::{Instant};
    use std::thread;
    use std::time::Duration;
    
    fn my_fun() {
        // Put your code here
    }
    
    fn main() {
        let current = Instant::now();
        
        my_fun();
        
        let duration = current.elapsed();
        
        println!("Time elapsed in MyFun() is: {:?}", duration);
    }
    

    Run this program with your implementations.