Why is my swap <string, string> much 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 1,000,000 times and it averaged 78 ms, but std just took 13 ms. I just looked at the std::swap implementation, I found that it is the same as mine, so why am I so slow?

+6
source share
1 answer

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: lhs.swap(rhs);

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

Possible implementation:

 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, I assume that even if you move one line to another, the destructor for the temporary line will still be called. Something that doesn't match the STL compatible implementation above.

+5
source

Source: https://habr.com/ru/post/1014748/


All Articles