为什么我的交换<字符串,字符串>比标准版本慢得多?
Why is my swap<string,string> far slower than the std version?
这是我的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兼容实现中,情况并非如此。
相关文章:
- 如何在C++中将 Python 字符串转换为其转义版本?
- c 字符串 c++ 中 strlen 的递归版本
- 在 cpp 自己的版本中对字符串进行哈希处理
- 比较版本号字符串
- 如何在yaml-cpp中写一个版本字符串作为文字(不是字符串)
- 从版本字符串中提取 OpenGL 版本
- 将词法分析器字符串累加器移植到新版本的 Quex 时出现问题
- 如何在C 中输出两个字符串版本,一个具有逃生字符,另一个则不是
- 为什么我的交换<字符串,字符串>比标准版本慢得多?
- 不同编译器版本的C++中的奇怪行为(字符串通过引用传递):参见简单的程序说明
- 字符串搜索 - 并行版本较慢
- 如何使用Boost Ptree来解析像中国人这样的宽字节字符串?Boost版本是Boost_1_64_0
- p = new String [0]和p = new Int [0]之后,为什么当删除[] p时字符串版本崩溃
- 无法使用String.Format在WPF中显示版本字符串
- 尝试使用C++实现检测字符串中回文的递归版本.在这里遇到了一些麻烦
- 使用C++预处理器从单独的组件构造版本字符串
- 如何在 c++ 中拆分字符串而不将其他库安装到标准 Ubuntu 版本
- 隐藏或删除不需要的字符串从 Windows 可执行文件版本中
- C++11 字符串属性和 gcc 版本
- 我想创建一个函数,我可以在其中输入一个字符串,它会输出一个混乱的字符串版本