D
Denis Remezov
Steve said:Hi,
I'm using a std::vector to store a list of user defined objects. The vector
may have well over 1000 elements, and I'm suffering a performance hit. If I
use push_back I get a much worse perfomance than if I first define the
vector of a given size, then write to the elements with myvec =
However, I'm currently thinking that it isn't feasible to obtain the vector
size, so really need to resize the vector dynamically as I go. Is push_back
the fastest function to add elements to the end of a vector, or is there a
faster way (a different container, maybe)?
Although it periodically causes reallocations, push_back() is still an amortised
constant time operation. reserve() can help to cut on the number of reallocations
if you can estimate the expected number of elements to be added.
How expensive is a copying of an element? If the objects are large enough or
if the copy constructor does a lot of work, it may be better to use a vector of
pointers to objects rather than a vector of objects themselves.
Another way to avoid copying is to use an std::list. You haven't mentioned if you
really needed random access to the elements. If not, a list could be the right
thing, especially if the objects are not too small or are expensive to copy.
I've also seen this with the std::string object. I have a function called
GetFloat, which extracts a space delimited float from a text string:
float GetFloat(const string& Str, const int& Spaces, bool& Valid)
{
int ColPosition = GetNewPosition(Str, Spaces); // convert spaces to
chars
if(ColPosition == -1) {
Valid = false;
return 0.0;
}
std::string s;
std::string::const_iterator p = Str.begin() + ColPosition;
while(*p != ' ' && p != Str.end()) {
if(*p == 'I') { Valid = false; return 0.0; }
if(*p != ' ') s.push_back(*p); <============
alternatives below
++p;
}
I think the above should be
while(p != Str.end() && *p != ' ') {
if(*p == 'I') { Valid = false; return 0.0; }
s.push_back(*p);
++p;
}
Valid = true;
return atof(s.c_str());
}
for s, if I make it a fixed length and use s = ... it runs rather faster
than the above. Also s+=(*p) runs slightly faster than above, but not as
fast as s = ...
This function may be called thousands of times during my program (loading a
data file) and perhaps this is why the difference is significant. Is this
what I should expect to see, I thought they should be similar?
Reuse the same object s for multiple invocations, increasing its size when
needed. A static variable is a simple solution. If it isn't adequate, define
a class instead of a function, make s a member. I'd use a vector for s instead
of a string.
Denis