What (if any) performance advantages are offered by using iterators. It seems like the 'Right Way' to solve many problems, but does it create faster/more memory-conscious code? I'm thinking specifically in Python, but don't restrict answers to just that.
Benefits of Iterators. Use of an iterator simplifies the code and makes it general. Benefits of using this iterator API include: treats variables of all types, sizes, and shapes uniformly, whether they fit in memory or not, even if a single row won't fit in memory.
Iterator and for-each loop are faster than simple for loop for collections with no random access, while in collections which allows random access there is no performance change with for-each loop/for loop/iterator.
Iterators have several advantages: Cleaner code. Iterators can work with infinite sequences. Iterators save resources.
9 Answers. Show activity on this post. Iterator is faster for collections with no random access (e.g. TreeSet, HashMap, LinkedList). For arrays and ArrayLists, performance differences should be negligible.
There's actually a very good mail on the python mailing list about this: Iterators vs Lists. It's a bit dated (from 2003), but as far as I know, it's still valid.
Here's the summary:
For small datasets, iterator and list based approaches have similar performance. For larger datasets, iterators save both time and space.
What I would draw from it is this: iterators are to be preferred over loading data into a list if possible. But unless you have a big dataset, don't contort your code to make something that should fit in a list to work with an iterator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With