# Speed comparison between vector and 2*2 array

This is a discussion on Speed comparison between vector and 2*2 array within the C++ Programming forums, part of the General Programming Boards category; I'm refactoring someone else's code, and this code uses an underlying 1D vector to implement a 2D array. If the ...

1. ## Speed comparison between vector and 2*2 array

I'm refactoring someone else's code, and this code uses an underlying 1D vector to implement a 2D array. If the 2D arrays were variable in size, I'd leave it alone, but the sizes of these "arrays" are pretty much set in stone, so there's no problem changing them to straightforward 2D arrays (which I am aware are still 1D arrays in memory). Now, if I had the time, I'd do speed tests myself, but I am on a deadline, so I'm asking you experts' advice.
In a program that does several million iterations over these arrays (101 by 101 to be precise), would there be a significant speed gain if I switched from vectors to arrays?

2. Possibly, but not because of the vector. It might be faster if the current inner dimension is not a real constant. (simulated 2d access is outer_index * inner_dimension + inner_index) Having inner_dimension a real constant (const int inner_dimension = whatever) might give the compiler opportunity to generate some smart opcodes. With a static array, you're guaranteed to have a constant.

Other than that, the only reason I can see for it being faster is stupid compilers.

3. The access speed of already allocated vectors should be identical to arrays. The vector is basically a wrapper around an array allocated with new[]. As long as the vector is not being resized all the time you should see no difference.

4. Thanks. Good to know that I can get speed benefits while working less.

5. You said that the size is set in stone. That means it is known at compile time? Then you are comparing a static array with vector (as opposed to a dynamic array allocated with new[]), right?

I'd imagine the static array is actually faster. Whether the difference is noticeable or not I don't know, but if you were starting from scratch I'd say use a plain array or std::tr1::array (i.e. boost's array).