C++: array vs vector

Joined
Oct 10, 2006
Messages
3
Reaction score
0
Hi, I am trying to analyze the difference in performance from using vector vs using array in C++ with the following simple program:

array
-------
int main(){
static const int SIZE = 10000;

int arr[SIZE];
int i,j;

arr[SIZE-1] = 0; //prevent paging effects

for(i=0; i < 50000; i++){
for(j=0; j < SIZE; j++){
arr[j] = j;
} //for j
} //for i

} //main

vector
-------
#include <vector>
using std::vector;

int main(){
static const int SIZE = 10000;

vector<int> arr( SIZE );
int i,j;

arr[SIZE-1] = 0; //prevent paging effects

for(i=0; i < 50000; i++){
for(j=0; j < SIZE; j++){
arr[j] = j;
} //for j
} //for i

} //main

I ran the program and time it using 'time' on UNIX, and getting the results that array performs better than vector, with array it executes in 25.0u while with vector it takes 145.0u

I am guessing this is because vector does a dynamic memory allocation, but I am not so sure, could someone please elaborate on this one ?

Another question, the same program above is compiled using compiler optimization flag -O2, now running the program with 3 different values of the outer loop (50000, 500000, 5000000), both vectors and array keep giving me the same timing, why is this so ?

Thank you so much =)
 
Joined
Oct 10, 2006
Messages
3
Reaction score
0
C++ Vector: operator[] vs at(...)

From my previous thread, I was analyzing array vs vector, I am also analyzing the difference in performance in vector access with operator[] vs at(...) method call:

for(j=0; j < SIZE; j++){
arr[j] = j;
} //for j

compare to:

for(j=0; j < SIZE; j++){
arr.at(j) = j;
} //for j

the operator[] performs more efficiently, my answer is that it's due to the fact that at(...) does a boundary checking on runtime, while operator[] doesnt

but is there any other reason than the checking ?

Thank you
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top