std::vector::reserve performance penalty

后端 未结 6 736
感动是毒
感动是毒 2021-01-05 02:19
inline void add(const DataStruct& rhs) {
   using namespace boost::assign;
   vec.reserve(vec.size() + 3);
   vec += rhs.a, rhs.b, rhs.c;
}

The

6条回答
  •  攒了一身酷
    2021-01-05 02:38

    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.

提交回复
热议问题