C++ ranges are better than iterators?
Or one more way to destroy performance with "zero-cost abstractions".
std;:ranges was one of the major most expected features of C++20. It promised concise way to compose computations that enables all sorts of compiler optimizations. It’s not your old style iterators introduced and popularized by Alex Stepanov, with their no longer popular mechanical sympathy.
But to check their might, today we won’t deal with complex examples, and, instead, will look at a trivial task all of us probably had to do at some point of our career - summing positive numbers.
First, let’s start with old style
Oh no, just look at this terrible and hard to read old-style code with its if. Range-based version looks so much better
Well, ok, maybe it doesn’t look any better. Things would have been better if C++20 had accumulate or reduce algorithm for ranges, but in C++20 for loop is the way to go unless we are willing to use some external libraries. Good thing that it’s a zero-cost abstraction and is as efficient as old-style version, right? Let’s see. The inner loop of the old-style looks just like we’d expect - vectorized and efficient.
The range-based version looks suspiciously different and without any SIMD instructions
What does it mean in practice?
The lack of vectorization should have already set our expectations accordingly, so the 3.1X slower results don’t come as a surprise.
So, as always, don’t take anyone’s word when it comes to performance - use compiler explorer and benchmark to find out what works best for your use-case.
Btw, it’s technically possible to “fix” range-based version so that it’s vectorized and you can check
to learn how, but the point of this article is to remind you about the fact that there is no such thing as “zero-cost abstraction” and don’t use features just because they are new or popular. There are legitimate use-cases that are much easier to model using ranges and are easy to optimize for compilers and benefit both readability and performance, but design considerations are usually a better method of technology selection than a fashion trend.
Good to know.