Optimize “for” loop

后端 未结 3 1837
醉话见心
醉话见心 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:59

    I have checked with GCC explorer:

    Code entered:

    #include
    
    int sum(const std::vector & someVector) {
      int s = 0;
      for (int i = 0; i < someVector.size(); i++) {
        s += someVector[i];
      }
      return s;
    }
    
    int main() {
      std::vector 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.

提交回复
热议问题