Using arrays or std::vectors in C++, what's the performance gap?

后端 未结 19 1475
忘了有多久
忘了有多久 2020-11-22 03:23

In our C++ course they suggest not to use C++ arrays on new projects anymore. As far as I know Stroustroup himself suggests not to use arrays. But are there significant perf

19条回答
  •  旧时难觅i
    2020-11-22 04:07

    Sometimes arrays are indeed better than vectors. If you are always manipulating a fixed length set of objects, arrays are better. Consider the following code snippets:

    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;
    
    }
    

    where the vector version of X is

    class X {
    vector vec;
    public:
    X(const vector& v) {vec = v;}
    int first() { return vec[0];}
    };
    

    and the array version of X is:

    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];}
    };
    

    The array version will of main() will be faster because we are avoiding the overhead of "new" everytime in the inner loop.

    (This code was posted to comp.lang.c++ by me).

提交回复
热议问题