user3126461
user3126461

Reputation: 152

Why is my swap<string,string> far slower than the std version?

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 std one just took 13ms. I just looked at the implementation of std::swap, I found it just the the same as mine, so why is mine so slow?

Upvotes: 6

Views: 396

Answers (1)

Dimitrios Bouzas
Dimitrios Bouzas

Reputation: 42909

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)
noexcept(noexcept(lhs.swap(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> 
inline
void
swap(std::basic_string<Elem, Traits, Alloc>& left, 
     std::basic_string<Elem, Traits, Alloc>& right) noexcept(noexcept(left.swap(right))) {
  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.

Upvotes: 7

Related Questions