Vector initialisation using ranges vs lambda inline initialisation
I would like to initialise a vector by transforming the other one. I made a test with two ways of inline initialisation a transformed std::vector
.
One using lambda inline initialisation (with std::transform
):
std::vector<int> foo(100,42);
const auto fooTimesTwo = [&]{
std::vector<int> tmp(foo.size());
std::transform(foo.begin(), foo.end(), tmp.begin(), convert);
return tmp;
}();
And the other one - using std::ranges::views::transform
:
std::vector<int> foo(100,42);
auto transform_range = (foo | std::ranges::views::transform(convert));
std::vector<int> fooTimesTwo {
transform_range.begin(),
transform_range.end()
};
I expected that both way of vector initialisation should have similar performance, but from some reason the benchmark of solution with traditional std::transform
is much faster that the second one (9.7 times faster -> https://quick-bench.com/q/3PSDRO9UbMNunUpdWGNShF49WlQ ).
My questions are:
- Do I use
std::ranges::views::transform
incorrectly? - Why does it work so much slower?
Side note - it can be done using boost::make_transform_iterator
, but I couldn't check it on quick-bench as they don't support boost. So I'm not sure about efficiency of such solution.
convert
doing? – JHBonarius Apr 13 at 20:32