Thread: Speed comparison between vector and 2*2 array

  1. #1
    Registered User
    Join Date
    Oct 2005
    Posts
    271

    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. #2
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    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.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  3. #3
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    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. #4
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545

  5. #5
    Registered User
    Join Date
    Oct 2005
    Posts
    271
    Thanks. Good to know that I can get speed benefits while working less.

  6. #6
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    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).

Popular pages Recent additions subscribe to a feed