TITLE: STL performance of resize() and reserve() (Newsgroups: comp.lang.c++, 27 Apr 2000) OLIVER: Bill Oliver >>template >>amoeba::amoeba(const amoeba& a){ >> species = a.species; >> size = a.size; >> >> ... >> >> int numparents = a.parents.size(); >> parents.resize(numparents); >> std::copy(a.parents.begin(), a.parents.end(), parents.begin()); >>} >> >>This insures the memory allocation for 'parents' occurs only once, >>while the push_back routine you had could theoretically allocate and >>copy with every iteration of the loop (any decent implementation will >>overallocate to prevent this, but with a large vector you're still >>likely to allocate and copy numerous times). KOENIG: ark@research.att.com (Andrew Koenig) There are two significant mistakes here. First, the definition of vector is such that, if correctly implemented, successive calls to push_back will be no worse than a constant factor slower than if the vector was never reallocated at all. Of course, there's no guarantee of correct implementation, but it's worth noting anyway. Second, you should generally not use resize() because doing so allocates a bunch of elements that are then overwritten. Rather, you should use reserve() and push_back(). Calling reserve() allocates enough memory to hold the requested number of objects, but without putting any objects there. Successive calls to push_back will then not go through reallocation. _______________________________________________ cpptips mailing list http://cpptips.hyperformix.com