std :: vector ::保留性能惩罚 [英] std::vector::reserve performance penalty

查看:254
本文介绍了std :: vector ::保留性能惩罚的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

inline void add(const DataStruct& rhs) {
   using namespace boost::assign;
   vec.reserve(vec.size() + 3);
   vec += rhs.a, rhs.b, rhs.c;
}

上述函数执行了大约17000次,我可以看到,有一些转换涉及)约2个级别更糟糕调用vector :: reserve。

The above function was executed for about 17000 times and it performed (as far as I can see. There was some transformation involved) about 2 magnitudes worse with the call to vector::reserve.

我总是认为reserve可以加快push_back,即使对于小的值,但这似乎不是真的,我找不到任何明显的原因,它应该不是这样。存储是否阻止函数的内联?是调用size()太贵了吗?这取决于平台吗?

I always was under the impression that reserve can speed up push_back even for small values but this doesn't seem true and I can't find any obvious reasons why it shouldn't be this way. Does reserve prevent the inlining of the function? Is the call to size() too expensive? Does this depend on the platform? I'll try and code up some small benchmark to confirm this in a clean environment.

编译器: gcc(GCC)4.4.2

Compiler: gcc (GCC) 4.4.2 with -g -O2

推荐答案

reserve c $ c>将分配确切数量的元素,而 push_back()将通过加倍倍增内部缓冲区的指数增长,所以你将击败指数增长并强制重新分配/复制每次迭代。在 ltrace valgrind 下运行测试,并查看 malloc()呼叫。

GCC implementation of reserve() will allocate exact number of elements, while push_back() will grow internal buffer exponentially by doubling it, so you are defeating the exponential growth and forcing reallocation/copy on each iteration. Run your test under ltrace or valgrind and see the number of malloc() calls.

这篇关于std :: vector ::保留性能惩罚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆