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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With