Using ranges or algorithms has several advantages over raw loops, notably readability. On the other hand, as we’ve just seen, sheer performance is not necessarily among those advantages. Using ranges can be slightly slower than a raw loop version. But that’s not necessarily a problem, it really depends on your use case. Most probably it won’t make a bit difference.
Raw Loops for Performance?
by Sandor Dargo
From the article:
To my greatest satisfaction, I’ve recently joined a new project. I started to read through the codebase before joining and at that stage, whenever I saw a possibility for a minor improvement, I raised a tiny pull request. One of my pet peeves is rooted in Sean Parent’s 2013 talk at GoingNative, Seasoning C++ where he advocated for no raw loops.
When I saw this loop, I started to think about how to replace it:
Please note that the example is simplified and slightly changed so that it compiles on its own.
Let’s focus on
foo
, the rest is there just to make the example compilable.It seems that we could use
std::transform
. But heck, we use C++20 we have ranges at our hands so let’s go withstd::ranges::transform
!
Add a Comment
Comments are closed.