Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimize "for" loop

std::vector<int> someVector;    
for (unsigned int i = 0; i < someVector.size(); i++)
{
   // do something
}

Does the value of someVector.size() get calculated every time?

like image 584
Maria Ines Parnisari Avatar asked Dec 27 '22 03:12

Maria Ines Parnisari


2 Answers

I have checked with GCC explorer:

Code entered:

#include<vector>

int sum(const std::vector<int> & someVector) {
  int s = 0;
  for (int i = 0; i < someVector.size(); i++) {
    s += someVector[i];
  }
  return s;
}

int main() {
  std::vector<int> someVector;
  return sum(someVector);
};

Assembly generated for sum():

  movq  (%rdi), %rcx
  movq  8(%rdi), %rdx
  xorl  %eax, %eax
  cmpq  %rcx, %rdx
  je    .LBB0_3
  subq  %rcx, %rdx
  sarq  $2, %rdx
  xorl  %eax, %eax
  xorl  %esi, %esi
.LBB0_2:                                # =>This Inner Loop Header: Depth=1
  addl  (%rcx,%rsi,4), %eax
  incq  %rsi
  cmpq  %rdx, %rsi
  jb    .LBB0_2
.LBB0_3:                                # %._crit_edge
  ret

i.e. the size is kept in %rdx -- there is no call to size() each time.

As others have pointed out already, results may depend on

  • your compiler,
  • optimization settings and
  • what you actually do in the loop (click the gcc explorer link above to try yourself).

Without calculating anything, the whole loop gets optimized away.

like image 168
Stefan Haustein Avatar answered Jan 13 '23 22:01

Stefan Haustein


Does the value of someVector.length() get calculated every time?

Possibly, depending on the contents of the loop and many other things. For instance, the size of the vector could be modified inside the loop. Then your compiler has to be able to spot if this is not the case. So a few conditions have to be met for this to be optimized out.

If you require that std::vector::size() is only called once in the loop, then the best (and only) strategy is to sidestep the question entirely through a trivial modification to the code:

std::vector<int> someVector;    
for (unsigned int i = 0, length = someVector.size(); i < length; ++i)
{
   // do something
}
like image 43
juanchopanza Avatar answered Jan 13 '23 22:01

juanchopanza