Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taking vector size() out of loop condition to optimize

Tags:

c++

fibs is a std::vector. Using g++, I was advised to take fibs.size() out of the loop, to save computing it each time (because the vector could change)

int sum = 0;
for(int i = 0; i < fibs.size(); ++i){
    if(fibs[i] % 2 == 0){
        sum += fibs[i];
    }
}

Surely there is some dataflow analysis in the compiler that would tell us that fibs won't change size. Is there? Or should I set some other variable to be fibs.size() and use that in the loop condition?

like image 925
oadams Avatar asked Dec 10 '22 07:12

oadams


1 Answers

The compiler will likely determine that it won't change. Even if it did, size() for vectors is an O(1) operation.

like image 93
Puppy Avatar answered Dec 25 '22 23:12

Puppy