Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

C++

Name: Snake4D 2012-04-11 17:38

A simple question...

is it better to traverse a std::vector like this:

std::vector<int> myvec;
//populate the vector
for(int i = 0; i < myvec.size(); ++i){
    myvec[i] += 1;
}


or is better like this?

std::vector<int> myvec;
typedef std::vector<int>::iterator IT_int;
for(IT_int it = myvec.begin(); it != myvec.end(); ++it){
     *it += 1;
}

Name: Anonymous 2012-04-11 18:14

#include <iostream>
#include <vector>
#include <ctime>

#define SIZETOTEST 100000

int main (int argc, char * const argv[]) {
   
    std::vector<int> myvec;
    int myarray[SIZETOTEST];
   
    for (int i = 0; i < SIZETOTEST; ++i) {
        myvec.push_back(i);
        myarray[i] = i;
    }
    typedef std::vector<int>::iterator IT_int;
   
    clock_t start,end;
   
    start = std::clock();
    for (IT_int it = myvec.begin(); it != myvec.end(); ++it) {
        *it += 1;
    }
    end = std::clock();
   
    std::cout << "iterator it:   " << end - start << std::endl;
   
    start = std::clock();
    for (int i = 0; i < myvec.size(); ++i) {
        myvec[i] += 1;
    }
    end = std::clock();
   
    std::cout << "int i:         "<< end - start << std::endl;
   
    start = std::clock();
    for (int i = 0; i < SIZETOTEST; ++i) {
        myarray[i] = myarray[i] + 1;
    }
    end = std::clock();
    std::cout << "c-style array: " << end - start << std::endl;
   
    return 0;
}


a little deeper analysis:
in debug mode (no or really few optimization):

iterator it:   2430
int i:         1141
c-style array: 561


in release mode:

iterator it:   108
int i:         160
c-style array: 2


amazing... the iterator get faster than the normal access... (the c_style array optimization is also crazy...)

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List