Understanding the purpose of generator functions

Viewed 130

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?

1 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.

Related