优化“for”循环 [英] Optimize "for" loop

查看:107
本文介绍了优化“for”循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

someVector.size()的值每次都会计算

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

推荐答案


someVector.length

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.

如果你需要 std :: vector :: size()只在循环中调用一次,那么最好的(也是唯一的)策略是通过对代码进行一个简单的修改来回避问题:

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
}

这篇关于优化“for”循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆