Performance issue for vector::size() in a loop in C++

前端 未结 10 774
离开以前
离开以前 2020-11-29 04:37

In the following code:

std::vector var;
for (int i = 0; i < var.size(); i++);

Is the

10条回答
  •  离开以前
    2020-11-29 05:03

    Tested it for 900k iterations Its taking time 43 seconds for pre-calculated size and 42 seconds for using the size() call.

    If you guaranteed vector size doesn't change in the loop, better to use pre-calculated size otherwise there is no choice and must use size().

    #include 
    #include 
    
    using namespace std;
    
    int main() {
    vector v;
    
    for (int i = 0; i < 30000; i++)
            v.push_back(i);
    
    const size_t v_size = v.size();
    for(int i = 0; i < v_size; i++)
            for(int j = 0; j < v_size; j++)
                    cout << "";
    
    //for(int i = 0; i < v.size(); i++)
    //      for(int j = 0; j < v.size(); j++)
    //              cout << "";
    }
    

提交回复
热议问题