vector :: size()在循环中的性能问题 [英] Performance issue for vector::size() in a loop

查看:1491
本文介绍了vector :: size()在循环中的性能问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

hi when have a
vector< int> var;
for(int i = 0; i< var.size(); i ++) c> size()每次调用或只调用一次?

hi when having a vector<int> var; for(int i=0; i< var.size();i++) , is the size() function called each time or only once ?

我想我最好使用迭代器,或者只是在循环之前有变量

from the answers I guess I better use iterators , or just have variable before the loop

推荐答案

在理论上,每次都会调用自for循环:

In theory, it is called each time, since a for loop:

for(initialization; condition; increment)
    body;

已扩展为

{
    initialization;
    while(condition)
    {
        body;
        increment;
    }
}

(注意花括号,因为初始化已经在内部范围)

(notice the curly braces, because initialization is already in an inner scope)

在实践中,如果编译器理解你的一部分条件在循环的所有持续时间是不变的, em>它没有副作用,它可以聪明到足以把它移出。这通常用 strlen 和其中没有写其参数的循环中的那些(编译器知道很好)来完成。

In practice, if the compiler understands that a piece of your condition is invariant through all the duration of the loop and it does not have side-effects, it can be smart enough to move it out. This is routinely done with strlen and things like that (that the compiler knows well) in loops where its argument isn't written.

如果你知道你的条件的一部分是昂贵的来评估(这样的条件不是,因为它通常归结为一个指针减法,几乎肯定是内联的) )。

Doing that optimization by hand is worthy if you know that a part of your condition is "expensive" to evaluate (and such condition isn't, since it usually boils down to a pointer subtraction, which is almost surely inlined).

编辑:迭代器,但对于向量 s没有那么重要,因为通过 operator [] 对元素的随机访问被保证为O(1);实际上具有向量,它通常是指针sum(向量基础+索引)和解引用指针 increment (前面的元素+1)和迭代器的解引用。由于目标地址仍然是相同的,我不认为你可以从缓存局部性方面获得迭代器的东西(即使如此,如果你不是在严格的循环中走大数组,你甚至不应该注意到

as others said, in general with containers it's better to use iterators, but for vectors it's not so important, because random access to elements via operator[] is guaranteed to be O(1); actually with vectors it usually is a pointer sum (vector base+index) and dereference vs the pointer increment (preceding element+1) and dereference of iterators. Since the target address is still the same, I don't think that you can gain something from iterators in terms of cache locality (and even if so, if you're not walking big arrays in tight loops you shouldn't even notice such kind of improvements).

对于列表和其他容器,使用迭代器而不是随机访问可以真的重要,因为使用随机访问可能意味着每次列表的时候,递增一个迭代器只是一个指针解引用。

For lists and other containers, instead, using iterators instead of random access can be really important, since using random access may mean walk every time the list, while incrementing an iterator is just a pointer dereference.

这篇关于vector :: size()在循环中的性能问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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