简体   繁体   中英

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 ?

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

ie 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.

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
}

It depends on the compiler optimization.

it might Loop optimization,(if possible not mentioned something like volatile)

the compiler will put datas (irrelevant) not dependent on loop outside.

so it may generate something like

int length = someVector.length();
for (unsigned int i = 0; i < length; i++)
{
    // do something
}

There are many compiler optimization techniques that it 'll do.

By default in c++ there are some "pure functions" string.length() which is always optimized. i'm not sure whether vector.size belong to that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM