Re: Need to understand tradeoff between array and vector
On Nov 22, 4:01 pm, duli <dulipi...@gmail.com> wrote:
Hi:
I have a need for fixed length vector of integers (say 3 ints) and
want to find out which is better to use: arrays or vectors.
I am noticing a big difference in performance and wrote test code to
illustrate this (written below). The time difference is huge
(about a 40 fold better performance for array).
Try compiling in release mode.
A vector's construction and copying will always be slower than a
primitive array.
So I am confused: I remember Stroustrup saying that one should always
use vectors instead of arrays.
vectors and arrays are 2 different beasts. When a primitive array is
required, choose it over a vector. Arrays usually mean more code, more
work. A vector has a lot to offer other than the fact that its
dynamic.
range_checked accessor using at(index), reserve() to set capacity,
iteration using begin() and end(), object construction using a non-
default ctor, a number of predefined operators and algorithms, etc
What would happen if we did not know the length of the array at
compile time ?
you would allocate a dynamic array, that means you need to manage the
allocations manually.
const int length(50000);
int* arr = new int[ length ];
with a vector you can initialize it in one line and its still dynamic.
std::vector< double > v(50000, 1.1);
Thanks
Duli.
Vector version:
class X {
vector<int> vec;
public:
X(const vector<int>& v) {vec = v;}
// use init list
X(const vector<int>& v) : vec(v) { }
int first() { return vec[0];}
};
int main() {
vector<int> v;
v.resize(3);
v[0]=1; v[1]=2;v[2]=3;
int sum;
int starttime=time(NULL);
cout << starttime << endl;
for (int i=0;i<50000;i++)
for (int j=0;j<10000;j++) {
X x(v);
sum+=x.first();
}
int endtime=time(NULL);
cout << endtime << endl;
cout << endtime - starttime << endl;
}
Array version:
class X {
int f[3];
public:
X(int a[]) {f[0]=a[0]; f[1]=a[1];f[2]=a[2];}
int first() { return f[0];}
};
int main() {
int v[3];
v[0]=1; v[1]=2;v[2]=3;
int sum;
int starttime=time(NULL);
cout << starttime << endl;
for (int i=0;i<50000;i++)
for (int j=0;j<10000;j++) {
X x(v);
sum+=x.first();
}
int endtime=time(NULL);
cout << endtime << endl;
cout << endtime - starttime << endl;
}