Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the purpose of generator functions

Tags:

flutter

dart

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?

like image 291
Brendon Cheung Avatar asked Nov 15 '25 12:11

Brendon Cheung


2 Answers

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.

like image 184
blackkara Avatar answered Nov 18 '25 18:11

blackkara


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));
}
like image 42
ЯДPTГФИ Avatar answered Nov 18 '25 19:11

ЯДPTГФИ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!