mercredi 6 septembre 2017

Unexpectedly poor execution time for string concatenation function

I wrote the following string concatenation function (join) to reduce the number of allocations and the time spent for constructing the final string. I also wanted to write an easy to use appending function (one-liner if possible).

size_t str_size(const char *str) {
    return std::strlen(str);
}

size_t str_size(const std::string &str) {
    return str.size();
}

template <typename T>
size_t accumulated_size(const T& last) {
    return str_size(last);
}

template <typename T, typename... Args>
size_t accumulated_size(const T& first, const Args& ...args) {
    return str_size(first) + accumulated_size(args...);
}

template <typename T>
void append(std::string& final_string, const T &last) {
    final_string += last;
}

template <typename T, typename... Args>
void append(std::string& final_string, const T& first, const Args& ...args) {
    final_string += first;
    append(final_string, args...);
}

template <typename T, typename... Args>
std::string join(const T& first, const Args& ...args) {
    std::string final_string;

    final_string.reserve(accumulated_size(first, args...));
    append(final_string, first, args...);

    return std::move(final_string);
}

I tested the join method against typical built-in C++ concatenation functionality using the operator+= and also the operator+ of the std::string class on a fairly large amount of strings (> 30). How and why is my method yielding poorer results in terms of time execution compared to the plain operator+= or operator+ approach?

Aucun commentaire:

Enregistrer un commentaire