More efficient way to call vector.size()

Viewed 160

Given a vector of ints I saw my professor writing:

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

I argue that his code isn't efficient and could be replaced by the following, am I right?

int vect_size=vect.size();
for (int i=0;i<vect_size;++i)
{
}
2 Answers

Don't fall into premature optimization traps like this. Your compiler is more than capable of optimize those lines if needed (and if instructed).

There are other things that you should note.

  • Assuming that vect is a vector, std::vector::size() returns a size_t value, which is an unsigned type. Your compiler may warn you about the comparison i < vect.size() which involves variables of different signedness.
    If you really want i to be an int (there may be no reasons for it to be unsigned) you can use the following

    for ( int i = 0, v_size = vect.size(); i < v_size; ++i ) { /* ... */ }
    
  • Do you really need i at all? Since C++11 you can write range-based for loops and, in general, you may want(1) to use one of the algorithms provided by the Standard Library instead of a raw loop.

1) See e.g. this talk by Sean Parent.

You can do this:

for (std::size_t i = 0, vect_size = vect.size(); i < vect_size; ++i)
{
}

This way, you can limit the scope of vect_size.

Related