Search code examples
c++loopsc++11ranged-loops

C++ Ranged-based For Loop Efficiency


When I started learning Java the first time, I remember thinking of how I wanted a for-each loop in C++; however, now that they have been added and I am (marginally) wiser than before, I have to wonder if they are actually more efficient?

There are two cases I am curious about, the first is the traditional array, and the second is a dynamic sized object, like the std::vector.

I would predict that iterating over a traditional fixed-size array would be more efficient with a for loop, and dynamically allocated storage would be faster with the range-based loop.

int fvalues[NUMBER];
for(unsigned int x = 0; x < NUMBER; ++x) {
    //Do Stuff
}

for(auto&& i : fvalues) {
    //Do Stuff
}


std::vector<int> dvalues = std::vector<int>(NUMBER);
for(unsigned int x = 0; x < NUMBER; ++x) {
    //Do Stuff (not adding or removing from vector)
}

for(auto&& i : dvalues) {
    //Do Stuff (not adding or removing from vector)
}

Solution

  • Any difference is negligible at best. Using the following code:

    #include <cstdint>
    #include <cstddef>
    #include <ctime>
    #include <iostream>
    #include <vector>
    
    const size_t NUMBER = 1000000;
    
    int main() {
        time_t start;
        time_t finish;
    
    
        int fvalues[NUMBER];
    
    
        time(&start);
        for(unsigned int x = 0; x < NUMBER; ++x) {
            fvalues[x] = 3;
        }
        time(&finish);
    
        std::cout << "Fixed For: " << std::difftime(finish, start) << '\n';
    
        time(&start);
        for(auto&& i : fvalues) {
            i = 5;
        }
        time(&finish);
        std::cout << "Fixed Range: " << std::difftime(finish, start) << '\n';
    
        std::vector<int> dvalues;
        for(unsigned int x = 0; x < NUMBER; ++x) {
            dvalues.push_back(0);
        }
    
        time(&start);
        for(unsigned int x = 0; x < NUMBER; ++x) {
            dvalues[x] = 3;
        }
        time(&finish);
        std::cout << "Dynamic For: " << std::difftime(finish, start) << '\n';
    
        time(&start);
        for(auto&& i : dvalues) {
            i = 5;
        }
        time(&finish);
        std::cout << "Dynamic Range: " << std::difftime(finish, start) << '\n';
    }
    

    The result is always 0 for all tests. And timing the entire program (terminal time command) yields 0.033s of user time so the result is not surprising.