resize performance for std::vector in C++

I am working on an iOS port of my Android game Concussion Boxing.

Inside my rendering function I have a certain loop that use the same struct for each mesh that is drawn. This struct has std::vector variables of various kinds in it.

Whenever I want to use this struct to pass parameters to a function I would resize its std::vector variables.

Allocating memory is a CPU demanding operation that is why resize can be used to save on these allocation operations.

A good idea would be to declare the struct outside of the loop so we can reuse the memory that was allocated in the previous iteration of the loop.

However, there is a case in which resize won’t work so well. If you have a std::vector<std::vector<float>> then resize will have a performance hit.

I don’t know what is going inside resize in this case but I found that simpley having a pointer to float or a struct of a constant amount of floats(in an array) will be a lot more efficient rather than using a vector of a vector.

For reference, I improved my game’s frame CPU time from 27 ms to 22 ms by using less vectors of vectors.

std::vector resize bug

There is a certain bug that I keep making again and again.

In C++ there is a standard template library data structure called vector.

It is a data structure that gives you random access to it’s content, much like an array.

A vector can be of variable length and there are several ways to initialize and change it’s size. One of the methods to change it’s size is std::vector::resize.

The advantage of resize is that it can be used after the ctr. But there is a subtle point that needs to be considered.

When you resize std::vector it doesn’t necesseraly call the dtr of it’s content.

The most common issue of this for me is when I want to load new data to std::vector not realizing the old data is still there. Imagine we have std::vector<std::list<unsigned int> >.

After resizing the lists in this case might not be empty.

In order to make sure your vector is empty you should call std::vector::clear first.