Reputation: 553
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));
Upvotes: 3
Views: 2715
Reputation: 1483
Interestingly, the documentation for the for_each
method mentions that it can be faster than a normal for
This is equivalent to using a for loop on the iterator, although break and continue are not possible from a closure. It’s generally more idiomatic to use a for loop, but for_each may be more legible when processing items at the end of longer iterator chains. In some cases for_each may also be faster than a loop, because it will use internal iteration on adapters like Chain.
Source here
Upvotes: 1
Reputation: 408
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.
Upvotes: 6