Presenting the minimal code to describe the problem:
struct A {
vector<string> v;
// ... other data and methods
};
A obj;
ifstream file("some_file.txt");
char buffer[BIG_SIZE];
while( <big loop> ) {
file.getline(buffer, BIG_SIZE-1);
// process buffer; which may change its size
obj.v.push_back(buffer); // <------- can be optimized ??
}
...
Here 2 times string
creation happens; 1st time to create the actual string
object and 2nd time while copy constructing it for the vector
. Demo
The push_back()
operation happens millions of times and I am paying for one extra allocation those many times which is of no use for me.
Is there a way to optimize this ? I am open for any suitable change. (not categorizing this as premature optimization because push_back()
happens so many times throughout the code).