std::vector::reserve performance penalty

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

    When std::vector needs to reallocate it grows its allocation size by N*2, where n is its current size. This results in a logarithmic number of reallocs as the vector grows.

    If instead the std::vector grew its allocated space by a constant amount, the number of reallocs would grow linearly as the vector grows.

    What you've done is essentially cause the vector to grow by a constant amount 3, meaning linear growth. Linear is obviously worse that logarithmic, especially with big numbers.

    Generally, the only growth better than logarithmic is constant. That is why the standards committee created the reserve method. If you can avoid all reallocs (constant) you will perform better than the default logarithmic behavior.

    That said you may want to consider Herb Sutter's comments about preferring std::deque over vector www.gotw.ca/gotw/054.htm

提交回复
热议问题