I am learning about generator functions and in the documentation, generator functions are lazily evaluated but what is the benefit of this and why would you care? You will see this synchronous generator function:
Iterable<int> naturalsTo(int n) sync* {
int k = 0;
while (k < n) yield k++;
}
But what will be different if I do this?
Iterable<int> naturalsTo(int n) {
List<int> numbers = [];
for (int i = 0; i <= n; i++) {
numbers.add(i);
}
return numbers;
}
Both codes do exactly the same thing? Is there a memory advantage if I go for the generator function?
what will be the different if I do this?
The first one is a stream sync*, which means whenever yield called, it's subscriber receive values.
The second one is a normal method. It's caller has to wait until inner loop(in your case) completed.
Generator functions add values as they are generated, while standard functions add values all at once: into the return object.
Generator functions release memory used to yield values after sending them to a consumer, unlike standard functions that have hold all values in memory to return a collection.
The yield keyword is what generates values on-demand.
Iterable<int> listTo(int n) { //Standard function
List<int> numbers = [];
for (int i = 0; i <= n; i++) {
numbers.add(i);
}
return numbers; //Adds values to the return object at once.
}
Iterable<int> countTo() sync* { //Generator function
yield 0; //0 added to the return object and so on.
yield 1;
yield 2;
yield 3;
}
void main() {
print(countTo());
print(listTo(3));
}
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