Reputation:
I found asynchronous recursion in the dart language seems to be incredibly slow in the following code sample and I'd like to know why.
import "dart:async";
Stream<int> rec(int z) async* {
yield z;
if (z > 0) yield* rec(z - 1);
}
void main() {
Stream<int> stream = rec(10000);
stream.listen((int x) {
if (x % 1000 == 0) print(x);
});
}
I'm testing this on the dart vm, so I can't believe that there is a timer involved as it is likely to be in a js vm in the browser.
If yield * were efficient enough I think it could serve as a replacement for trampolining a recursive function to avoid stack size limitation, too.
Upvotes: 0
Views: 323
Reputation: 31229
Sounds like the following issue which has a long history. I recommend you to read the thread since I don't think I can make a resume here which would make it justice: https://github.com/dart-lang/sdk/issues/29189
I want to add that you example can also be written using sync* which are much faster but is of course not async:
Iterable<int> rec(int z) sync* {
yield z;
if (z > 0) yield* rec(z - 1);
}
void main() {
final stream = rec(10000);
stream.forEach((int x) {
if (x % 1000 == 0) print(x);
});
}
Upvotes: 0