Optimize “for” loop

后端 未结 3 1808
醉话见心
醉话见心 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 someVector;    
    for (unsigned int i = 0, length = someVector.size(); i < length; ++i)
    {
       // do something
    }
    

提交回复
热议问题