u/sebamestre

Quadratic behavior with nested generators?

Consider the type definition

struct list {
  list* next;
  int value;
};

I have heard the claim that this code:

generator<int> list_values(list& l) {
  co_yield l.value;
  if (l.next) {
    co_yield elements_of(list_values(*l.next));
  }
}

Has linear runtime, whereas this one:

generator<int> list_values(list& l) {
  co_yield l.value;
  if (l.next) {
    for (int x : list_values(*l.next)) {
      co_yield x;
    }
  }
}

Has quadratic runtime due to successive suspension/resumption of nested coroutines.

Is this true? Also I haven't actually found a good source for this claim except for a blog titled "C++ Coroutines Don't Spark Joy" but I am hoping there is something better out there

reddit.com
u/sebamestre — 6 hours ago