optimize behind code
不必要的初始化
有一些make_xxx的初始化,这种如果有原生数组之类的,可能会帮你memset,包括数组的resize
可以看一下catch2作者关于vector性能的一篇文章
所以,如果只是要一个buffer的话,尤其是动态分配的内存的话,其实malloc是更优秀的解法
1
2
auto buffer_size = 5*1024*1024;
std::unique_ptr<void, decltype(&std::free)> buffer(std::malloc(buffer_size), &std::free);
这里的原因其实跟c++里的值初始化有关系, 代码里其实可以看到用了值初始化
1
2
3
4
5
6
template <class _Tp>
inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_SINCE_CXX23 typename __unique_if<_Tp>::__unique_array_unknown_bound
make_unique(size_t __n) {
typedef __remove_extent_t<_Tp> _Up;
return unique_ptr<_Tp>(new _Up[__n]());
}
底下还有个不用初始化的
1
2
3
4
5
template <class _Tp>
_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX23 typename __unique_if<_Tp>::__unique_array_unknown_bound
make_unique_for_overwrite(size_t __n) {
return unique_ptr<_Tp>(new __remove_extent_t<_Tp>[__n]);
}
vector空间回收
shirnk_to_fit不一定是真回收了,因为这个标准就不是强制的,比较稳的清空是swap一次临时空数组
1
vector<int>().swap(vec);
另外,vector的clear,记得不一定是O(1)的,因为他会call析构函数,如果元素是很复杂的非POD类型的话,其实要考虑释放的时间
分支预测
This post is licensed under CC BY 4.0 by the author.