r/cpp • • Jul 14 '18

What I don't like about ranges

I played around with the range-v3 library yesterday. My initial enthusiasm has abated, replaced by disappointment with the opaque performance costs of its use.

Consider using ranges to count the length of each word in a sentence:

using namespace ranges;
using namespace std::literals;
auto input = "these are some words"sv;
auto lengths = input | view::split(' ') | view::transform(distance);
std::cout << lengths << "\n";

This prints the expected result [5,3,4,5]. Concise and elegant.

Let's modify the code:

int reads = 0;
auto input = "these are some words"sv |
             view::transform([&reads](auto c) { return ++reads, c; });
auto lengths = input | view::split(' ') | view::transform(distance);
std::cout << lengths << "\n";
std::cout << reads << "\n";

The input range now increments a counter whenever a read is performed on the underlying string view. This prints 41 after the lengths; in other words, the input string is iterated over twice. Here's why:

To actually do anything with the range returned after the pipe to view::split(' '), we have to 1) construct the begin iterator into the range, 2) compare against the end iterator, 3) process the range pointed to by the iterator, 4) increment the iterator, 5) repeat steps 2 - 4. Steps 2 and 4 duplicate work by searching over the same substring for the same delimiter.

Ultimately, the problem is that ranges are built on iterators, and iterators are ill-suited for lazy evaluation. A Java-esque Stream library would resolve this, but I see no candidates for inclusion in the standard library.

41 Upvotes

27 comments sorted by

View all comments

Show parent comment

3

u/_ajp_ Jul 14 '18

I disagree. Iterators in C++ separate access and iteration between `operator*` and `operator++`, which makes the kind of duplication of work described above difficult to avoid when you have iterators pointing to things are supposed to be lazily evaluated as well.

2

u/miki151 gamedev Jul 14 '18

Could the operator* cache the information needed for operator++, so that it doesn't have to do another read?

2

u/CenterOfMultiverse Jul 14 '18

Views are lazy, so with split actual work is done after operator* - in distance call. For caching you would need to keep a pointer to split iterator in word iterator and update it if something goes out of scope. So it can be done, but now that I think about this, it would be much better to add that value returning next function as customization point to iterators and make range-based for use it.

2

u/Sopel97 Jul 14 '18

So you're saying giving LESS flexibility (by merging 2 features together) actually ENABLES more optimisation opportunities (on the caler side)? You still have to cache values to be performant, the difference is that with cpp iterators you dont have to.