-
Notifications
You must be signed in to change notification settings - Fork 12.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Adding method to consume
an iterator efficiently
#64117
Comments
I suggest adding a method fn take_iter<T : Iterator>(iter: T) {
iter.consume(); // consumed
// do something else
} |
That call to a no-op closure will most certainly be optimized out in release builds. In the case of the code that you've provided using In either case, I think the proposed scenario does not deserve a separate method. If you find yourself in need of force-consuming an iterator that produces side effects, that is a strong hint that you should move the effectful operations (like |
Yea, most of the time a |
I recommend the idiom |
As @clarfon noted, this has been discussed before (#48945), leading to the current suggestion to use rust/src/libcore/iter/traits/iterator.rs Lines 1476 to 1477 in b9de4ef
As such I'm going to close this. |
Currently, mapping methods for iterator, e.g.
map
andfilter
are implemented in a lazy manner. Which means they would not be calculated until furtherconsumption
.However, sometimes it can be the case that given an
Iterator
(whatever it actually is) . we just wanted its side-effect and to simplyconsume
it. for instance :Currently, there're several ways of achieving this goal, for example :
While they're both usable, it's obvious that these methods are at the cost of efficiency,
for_each
yields a call to closure which is totally unnecessary, whilecount
finally counting the number of elements in vain.The text was updated successfully, but these errors were encountered: