c++performancevectorpush-back

Faster alternative to push_back(size is known)


I have a float vector. As I process certain data, I push it back.I always know what the size will be while declaring the vector.

For the largest case, it is 172,490,752 floats. This takes about eleven seconds just to push_back everything.

Is there a faster alternative, like a different data structure or something?


Solution

  • If you know the final size, then reserve() that size after you declare the vector. That way it only has to allocate memory once.

    Also, you may experiment with using emplace_back() although I doubt it will make any difference for a vector of float. But try it and benchmark it (with an optimized build of course - you are using an optimized build - right?).

    Another option when you know the size in advance is to use std::array.