std::vector::reserve performance penalty

后端 未结 6 755
感动是毒
感动是毒 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:39

    You only use reserve() if you know in advance the number of elements. In that case reserve() space for all elements at once.

    Otherwise just use push_back() and rely on the default strategy - it will reallocate exponentially and greatly reduce the number of reallocations at a cost of slightly suboptimal memory consumption.

提交回复
热议问题