Brendon Cheung
Brendon Cheung

Reputation: 1035

Understanding the purpose of generator functions

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?

Upvotes: 3

Views: 758

Answers (2)

ЯДPTГФИ
ЯДPTГФИ

Reputation: 79

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));
}

Upvotes: 0

blackkara
blackkara

Reputation: 5052

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.

Upvotes: 1

Related Questions