通过迭代器与通过运算符 []/索引访问 std::vector 的速度? [英] Speed accessing a std::vector by iterator vs by operator[]/index?

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

问题描述

说,我有一个

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),如果它的运行速度比它可以慢十倍,但只运行一次并且只需要 0.1 毫秒,谁在乎?对于 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 的速度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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