为什么我的交换<字符串,字符串>比标准版本慢得多?

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

本文关键字:字符串 版本 标准版 标准 gt 交换 我的 lt 为什么      更新时间:2023-10-16

这是我的C++代码:

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

我运行了1000000次这个函数,平均耗时78ms,但std只需要13ms。我刚看了std::swap的实现,发现它和我的一样,为什么我的这么慢?

根据标准§21.3.2.8/p1交换[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效果:等效于:lhs.swap(rhs);

因此,std::swap专门/具有std::string的重载,相当于调用成员函数std::basic_string::swap

一种可能的实施方式是:

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);
}

至于为什么你的实现速度较慢,我的猜测是,即使你把一个字符串移到另一个字符串,临时字符串的析构函数仍然会被调用。在上面的STL兼容实现中,情况并非如此。