Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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));
    
like image 254
yjlee Avatar asked Oct 16 '25 10:10

yjlee


1 Answers

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.

like image 116
René Avatar answered Oct 19 '25 02:10

René



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!