Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it more efficient to store vector size into an int variable when using it multiple times? [duplicate]

Tags:

c++

So if we have the code below:

vector<string> vec1;
//initialize vec1 to contain thousands of strings

for (int i = 0; i < vec1.size(); i++) {
    //.....
}

for (int j = 0; j < vec1.size(); j++){
   //......
}

Would it be faster to declare an int vec_size = vec1.size() and use it like so:

int vec_size = vec1.size();

for (int i = 0; i < vec_size; i++) {
        //.....
    }

for (int j = 0; j < vec_size; i++) {
        //.....
    }

and if so, why?

like image 928
user5482356 Avatar asked Oct 31 '25 16:10

user5482356


1 Answers

Depends on compiler optimization settings. At some optimization settings, the compiler may realize that the string is not changing and thus only call the function once.

In the for loop, the expression j < vec1.size() is called for each iteration. If the vector size doesn't change in the loop, that is a bunch of wasted function calls. Calling it once and assigning to a variable reduces the execution to one call of std::vector::size().

By the way, the size() method returns size_t, which is usually compatible with unsigned int. (vectors can't have a negative size).

So your loop should be:

const size_t vec_size = vec1.size();
for (unsigned int i = 0; i < vec_size; ++i)
{
  //...
}

The declaration of the vector size variable as a constant allows the compiler to perform more optimizations; your telling the compiler that the variable won't change its value.

like image 188
Thomas Matthews Avatar answered Nov 02 '25 05:11

Thomas Matthews