ranges-v3 much slower than raw for loop

215 Views Asked by At

I have a very basic example, just joining several strings into a bigger string, with a separator. I have implemented it using ranges and using a raw for loop, and measured performance using google benchmark. The ranges-v3 version is much slower than the for loop version, and I don't understand why.

Why is the ranges version slower? What is the extra work is doing compared to the for loop version?

#include <string>
#include <span>
#include <range/v3/view.hpp>
#include <range/v3/range/conversion.hpp>


struct Element {
    std::string name;
    std::string some_other_data_not_relevant_here;
};


std::string stack_to_path(std::span<const Element> stack) {
    return stack | ranges::views::transform(&Element::name)
                 | ranges::views::join('/')
                 | ranges::to<std::string>;
}

std::string stack_to_path_naive(std::span<const Element> stack) {
    std::string r;
    for (const Element& el : stack) {
        if (!r.empty())
            r += '/';
        r += el.name;
    }
    return r;
}

https://godbolt.org/z/6jWW9chhE

0

There are 0 best solutions below