Are const_iterators faster?

后端 未结 11 1883
挽巷
挽巷 2020-11-30 02:04

Our coding guidelines prefer const_iterator, because they are a little faster compared to a normal iterator. It seems like the compiler optimizes t

11条回答
  •  半阙折子戏
    2020-11-30 02:19

    I can't see why they would be - constness is a compile time check. But the obvious answer is to write a test.

    Edit: Here is my test - it gives identical timings on my machine:

    #include 
    #include 
    #include 
    using namespace std;;
    
    
    int main() {
        vector  v;
        const int BIG = 10000000;
        for ( int i = 0; i < BIG; i++ ) {
            v.push_back( i );
        }
        cout << "begin\n";
        int n = 0;
        time_t now = time(0);
        for ( int a = 0; a < 10; a++ ) {
            for( vector ::iterator it = v.begin(); it != v.end(); ++it ) {
                n += *it;
            }
        }
        cout << time(0) - now << "\n";
        now = time(0);
        for ( int a = 0; a < 10; a++ ) {
            for( vector ::const_iterator cit = v.begin(); cit != v.end(); ++cit ) {
                n += *cit;
            }
        }
        cout << time(0) - now << "\n";;
    
        return n != 0;
    
    }
    

提交回复
热议问题