When to use iterators vs. loops?

84 points Train_wreck1998

I frequently find myself using iterators when coding in Rust, even for the most minor things, mostly because of how easy it is. However, upon benchmarking some of my solutions against other code scripts that don't use iterators, I find that my iterator version is almost always slower.

  1. Are there general iterator functions that I should use the least? For instance, it's common practice to avoid using many \collect\\ functions in succession.
  2. Are there other guidelines I should be following? What other heuristics do people use to make the iterator vs. loop choice?
  3. Is there a tool that you use to analyze your iterators (like perf)? Right now, at my skill level, iterator functions seem like impenetrable black boxes.

I've read the textbook section; it doesn't say much about guidelines. Any resources like blog articles or books on this topic would be super helpful!

I've read the following posts before posting:

https://www.reddit.com/r/learnrust/comments/pcwp31/always\_use\_iterators\_over\_for\_loops/

https://www.reddit.com/r/rust/comments/9cy2zq/performance\_question\_terrible\_performance\_with/

https://medium.com/@veedrac/rust-is-slow-and-i-am-the-cure-32facc0fdcb

https://www.reddit.com/r/rust/comments/eiwhkn/why\_is\_iterator\_so\_much\_faster/

https://medium.com/@veedrac/rust-is-slow-and-i-am-the-cure-32facc0fdcb

​

The most frequent answer I find on Reddit is that the deciding factor is usually readability and that if I coded them up properly I should expect similar performance.

This post is ill-posed. But I'm looking for general tip-off points to write good efficient code. Any help is deeply appreciated.