karl88
karl88

Reputation: 351

Should I use std::vector + my own size variable or not?

Note: Performance is very critical in my application! Allocate enough buffer storage for the worst case scenario is a requirement to avoid reallocation.

Look at this, this is how I usually use std::vector:

//On startup...
unsigned int currVectorSize = 0u;
std::vector<MyStruct> myStructs;
myStructs.resize(...); //Allocate for the worst case scenario!

//Each frame, do this.
currVectorSize = 0u; //Reset vector, very fast.

run algorithm...
//insert X elements in myStructs if condition is met
myStructs[currVectorSize].member0 = ;
myStructs[currVectorSize].member1 = ;
myStructs[currVectorSize].member2 = ;
currVectorSize++;

run another algorithm...
//insert X elements in myStructs if condition is met
myStructs[currVectorSize].member0 = ;
myStructs[currVectorSize].member1 = ;
myStructs[currVectorSize].member2 = ;
currVectorSize++;

Another part of the application uses myStructs and currVectorSize

I have a decision problem, should I use std::vector + resize + my own size variable OR std::vector + reserve + push_back + clear + size?

I don't like to keep another size variable floating around, but the clear() function is slow(linear time) and the push_back function have the overhead of bounds check. I need to reset the size variable in constant time each frame without calling any destructors and running in linear time. Conclusion: I don't want to destroy my old data, I just need to reset the current size/current number inserted elements variable each frame.

Upvotes: 2

Views: 124

Answers (1)

Ap31
Ap31

Reputation: 3314

If performance is critical, then perhaps you should just profile everything you can.

Using your own size variable can help if you can be sure that no reallocation is needed beforehand (this is what you do - incrementing currVectorSize with no checks), but in this case why use std::vector at all? Just use an array or std::array.

Otherwise (if reallocation could happen) you would still need to compare your size variable to actual vector size, so this will be pretty much the same thing push_back does and will gain you nothing.

There are also some tweaked/optimized implementations of vector like folly::fbvector but you should carefully consider (and again, profile) wheter or not you need something like that.

As for clearing the vector, check out vector::resize - it is actually guaranteed not to reallocate if you're resizing down (due to iterator invalidation). So you can call resize(0) instead of clear just to be sure.

Upvotes: 0

Related Questions