user3126461 user3126461 - 4 years ago 120
C++ Question

why my swap<string,string> is far slower than the std one?

This is my C++ code:

inline static void swap(std::string& a1, std::string& a2) {
std::string temp( std::move(a1));
a1 = std::move( a2 );
a2 = std::move( temp );

I ran this function 1000000 times and it took 78ms on average, but the
one just took 13ms. I just looked at the implementation of
, I found it just the the same as mine, so why is mine so slow?


Answer Source

According to the standard ยง21.3.2.8/p1 swap [string.special] (Emphasis Mine):

template<class charT, class traits, class Allocator>
void swap(basic_string<charT, traits, Allocator>& lhs,
basic_string<charT, traits, Allocator>& rhs)

1 Effects: Equivalent to: lhs.swap(rhs);

Consequently, std::swap specializes/has an overload for std::string and is equivalent as calling the member function std::basic_string::swap.

A possible implementation would be:

template<class Elem, class Traits, class Alloc> 
swap(std::basic_string<Elem, Traits, Alloc>& left, 
     std::basic_string<Elem, Traits, Alloc>& right) noexcept(noexcept(left.swap(right))) {

As for why your implementation is slower, my guess is that even if you move the one string to the another, the destructor for the temporary string will still be called. Something that is not the case in the STL compatible implementation above.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download