速度访问std :: vector通过迭代器vs by operator [] / index? [英] Speed accessing a std::vector by iterator vs by operator[]/index?

查看:270
本文介绍了速度访问std :: vector通过迭代器vs by operator [] / index?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我有一个

std::vector<SomeClass *> v;

在我的代码中,我需要在程序中经常访问它的元素,循环向前和向后

in my code and I need to access its elements very often in the program, looping them forward and backward .

这两种类型之间访问类型最快?

Which is the fastest access type between those two ?

迭代器访问:

std::vector<SomeClass *> v;
std::vector<SomeClass *>::iterator i;
std::vector<SomeClass *>::reverse_iterator j;

// i loops forward, j loops backward
for( i = v.begin(), j = v.rbegin(); i != v.end() && j != v.rend(); i++, j++ ){
    // some operations on v items
}

下标存取(按索引)

std::vector<SomeClass *> v;
unsigned int i, j, size = v.size();

// i loops forward, j loops backward
for( i = 0, j = size - 1; i < size && j >= 0; i++, j-- ){
    // some operations on v items
}

,const_iterator是否提供更快的方式访问向量元素,以防我不必修改它们?

And, does const_iterator offer a faster way to access vector elements in case I do not have to modify them?

推荐答案

性能差异可能忽略或无(编译器可能优化它们是相同的);你应该担心其他事情,比如你的程序是否正确(一个缓慢但正确的程序比一个快速和不正确的程序更好)。使用迭代器还有其他优点,例如能够将底层容器更改为没有 operator [] 的容器而不修改循环。有关详情,请参见此问题

The performance difference is likely negligable or none (the compiler might optimise them to be identical); you should worry about other things, like whether your program is correct (a slow but correct program is better than a fast and incorrect program). There are other advantages to using iterators though, such as being able to change the underlying container to one with no operator[] without modifying your loops. See this question for more.

const_iterators与普通迭代器相比很可能没有或者可忽略的性能差异。它们旨在通过防止修改不应修改的内容(而不是性能)来提高程序的正确性。对于 const 关键字也是如此。

const_iterators will most likely have none, or negligable, performance difference compared to ordinary iterators. They are designed to improve the correctness of your program by preventing modifying things that shouldn't be modified, not for performance. The same goes for the const keyword in general.

总之,优化不应该是你的关注,直到发生了两件事:1)您注意到它运行得太慢了和2)你已经分析了瓶颈。对于1),如果它跑的速度比它可能10倍,但只有运行一次,需要0.1ms,谁在乎?对于2),确保它绝对是瓶颈,否则优化会对性能产生近乎无可衡量的效果。

In short, optimisation should not be a concern of yours until two things have happened: 1) you have noticed it runs too slowly and 2) you have profiled the bottlenecks. For 1), if it ran ten times slower than it could, but is only ever run once and takes 0.1ms, who cares? For 2), make sure it's definitely the bottleneck, otherwise optimising it will have nearly no measurable effect on performance!

这篇关于速度访问std :: vector通过迭代器vs by operator [] / index?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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