cpp23 std::generator efficiency vs (inherently) lazy views and other methods
Asked Answered
U

0

6

I am wondering how efficient the std::generator added in cpp23 standard, is going to compare with views. For example:

std::generator<int> f()
{
  int i = 10;
  while(true} {
    co_yield i; ++i;
  }
}
void use()
{
  auto g {f()};
  for (auto i = 0zu; i !=9; ++i)
  {
    std::cout << *g;
    // not sure what the syntax is here...
    ++g;
  }
}

vs

void use()
{
  auto r = std::views::iota(10);
  auto itr = r.begin();
  for (auto i = 0zu; i != 9; ++i)
  {
    std::cout << *itr;
    itr = std::next(itr);
  }
}

Which one, in theory could be more efficient, and what, if any, makes their efficiency different?

(Forgive my badly crafted toy example. One difference between using generator and the view is that the generator's state will not be able to be cleared(? I am speculating here. Correct me if I am wrong.) But for the sake of the comparison just assume use will only be called once, in both cases.)

Welcome any input or edit to the question/example as you see fit too!

Upspring answered 22/10, 2022 at 15:39 Comment(7)
Your first example is not remotely equivalent to your second. I'm not even sure std::generator has an operator<< overload. If it does, it would probably extract values until the generator is exhausted. Which you would then do 10 times. Unlike the iota example, where you only iterate over the range once.Dye
Also, your examples are too simplistic to offer any real comparison.Dye
Sorry for my first example. Edited. What I want is to have a producer that streams increasing integer values and then a consumer to consume until a point.Upspring
My point is, the genreator coroutine style of writing code seems easier and more alike the python kind of style ;) I just want to understand whether there are some hidden cost that we need to consider between writing it.Upspring
this simple case can also (easily) be achieved with lambda which I think would be most easy to optimize.Princeling
I know alternatives are present. If you look at presentation videos talking about generator as a new feature in cppcon23, their example are not very different from mine. I know they wanna give people idea of what new tools are available; I am trying to understand whether it, while looking good, does not add additional costs to user who can choose the alternatives.Upspring
@Upspring just point out there are things to compare other than range.Princeling

© 2022 - 2024 — McMap. All rights reserved.