use*_*461 6 c++ performance c++11
这是我的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 );
}
Run Code Online (Sandbox Code Playgroud)
我运行了这个功能1000000次,平均花了78ms,但是这只std花了13ms.我只是看了一下实现std::swap,我发现它跟我的一样,所以为什么我的这么慢?
根据标准§21.3.2.8/ p1 swap [string.special](Emphasis Mine):
Run Code Online (Sandbox Code Playgroud)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::swapspecializes /具有重载,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);
}
Run Code Online (Sandbox Code Playgroud)
至于为什么你的实现速度较慢,我的猜测是,即使你将一个字符串移动到另一个字符串,仍然会调用临时字符串的析构函数.在上面的STL兼容实现中不是这种情况.