std::vector::reserve performance penalty

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

    Move the reserve outside of the add.

    Each time you invoke "add", you are reserving atleast 3 extra elements. Depending on the implementation of vector, this could be increasing the size of the backing array almost every time you call "add". That is would definately cause the performance difference that you describe.

    The correct way to use reserve is something like:

    vec.reserve(max*3);
    for(int i=0; i

提交回复
热议问题