I have read discouraging statements about using plain arrays in c++. Where videogame development is involved we are aiming, as far as I know, at max speed execution. STL containers (such as std::vector) bring some elements not present in plain old arrays (iterators, etc). Does such functionality add overhead? (e.g. pointer chasing, etc) If so, is it worth it in real life to lose some speed in exchange for type safety?

  • \$\begingroup\$ Of course; you can't change arrays since they are static in initialisation. Sometimes, functionality is better preferred over overhead; and it's doubtful that the end-user would find any difference in what is used internally unless they have a very very bad CPU. Remember, a game will always be using the GPU (if using OpenGL/Direct3D) so what happens on the CPU side should not be a major concern unless there's a memory leak. I do give exceptions to use of threads, since games use a lot of processing power for them to be utilised. Go for it! \$\endgroup\$
    – Poriferous
    Feb 28 '15 at 13:16
  • \$\begingroup\$ Misuse of STL containers is slow. But if you use them as they were intended to, there should be no problem, moreover - this should be the last optimization you should ever be concerned about. Little overhead vs n^3 or exponential algorithm does not sound very significant. \$\endgroup\$
    – wondra
    Feb 28 '15 at 17:13

This depends on what operation you are performing on vectors. vectors are actually really fast. iteration is as fast as possible, since the vector does not store pointers but an array of objects in one straight block of memory, so iterating over a vertex is as fast as iterating over an array. And even the iterator-objects do not add a overhead, in production-mode (so if you don't compile in debug-mode), they do no runtime-checks but just trust you in what you're doing. Adding a new element is still really fast as long as it still fits in the allocated block of memory. If not, it either copies or moves the objects to a new block of memory, depending on if this class has a move-constructor and if it is noexcept. You can, of course, std::move your object in or even emplace_back (construct it right in place) so you don't even need to copy or with emplace_back not even to move. I'd never use plain arrays, they just need too much attention to not leak and not read from uninitialized memory, vectors will do all this for you. In debug-mode, vectors will perform boundary-checks when you access an element (i.e. with array-operator []), in non-debug mode they won't to give you best performance. vectors are awesome, just use them!


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.