Optimize “for” loop

后端 未结 3 1807
醉话见心
醉话见心 2021-01-13 19:31
std::vector someVector;    
for (unsigned int i = 0; i < someVector.size(); i++)
{
   // do something
}

Does the value of someV

相关标签:
3条回答
  • 2021-01-13 19:36

    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
    }
    
    0 讨论(0)
  • 2021-01-13 19:55

    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.

    0 讨论(0)
  • 2021-01-13 19:59

    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.

    0 讨论(0)
提交回复
热议问题