Quote:Original post by psyjax
Are STL Vectors slower than using standard arrays?
Ever since I found out about the vector container I have begun using them inplace of regular arrays. Is this wise in all cases?
I am just wondering because I have been using them to itterate thrugh vertexes in a 3D engine of mine. I want to know if this has any speed penalties.
The answer is "it depends". Creating a "normal" P.O.D. array on the stack is essentially "free". If you start creating vectors of objects in the same way, you may think it is basically the same situation, but using a vector this way is not "free". The vector has to allocate memory and check to see if it needs to grow every time you add something.
I'll give you an example. I have written many chess programs and other board game playing programs. One thing I need to do is generate a list of legal moves. This happens about one or two million times per second as the computer "thinks" about what move to play (searching a game tree). If I use a normal array to store the legal moves at each node of the game tree, that is a few million things for "free". If I replace the array with a vector, now I'm creating and destroying a vector a few million times per second and allocating/reallocating a few million times per second. When you go from "free" to "not free", there will be overhead. If you have a good STL implementation, a good compiler, and are willing to potentially create your own custom allocators or vector pools, you may be able to make it work with no noticable overhead.
The main question is: Can you avoid frequent allocation/reallocation in time critical parts of your code?
You can accomplish that if you either do your allocation when performance doesn't matter (like during a level change, or while my chess opponent is thinking about his own move), or by simply not reallocating (if you know you never have more than 2000 vertices, call reserve(2048) and it is likely you will never need to reallocate, and only once or twice if it happens).
Also beware of sub-par STL implementations and compilers that can't optimize away the abstraction. All of the memory pools or other cleverness in the world isn't going to produce fast code if the push_back() implementation does something stupidly slow.
And in the end, if you want to know for sure, the unfortunate answer is (like always)... "try it and see"