在访问数组比访问矢量快? [英] Is accessing an array is faster than accessing vector?

查看:107
本文介绍了在访问数组比访问矢量快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能显示的文件:结果
  <一href=\"http://stackoverflow.com/questions/381621/using-arrays-or-stdvectors-in-c-whats-the-performance-gap\">Using在C ++中的数组或std ::载体,有什么性能上的差距?结果
  <一href=\"http://stackoverflow.com/questions/3664272/stdvector-is-so-much-slower-than-plain-arrays\">std::vector不是普通阵,因此很慢?

内存1000元的矢量
[]数组是1000元的整数数组

memory is vector of 1000 elements array[] is an integer array of 1000 elements

for (iteration = 0; iteration < numiterations; iteration++) {
    for (j = 1; j < numints; j++) {
       memory[j] += memory[j - 1];
       //array[j] += array[j - 1];
    }
}

如果我运行100次迭代后比较for循环的时候,相比于载体的用于访问所需要的时间是非常小的。

If I compare the time of the for loop after running 100 iterations, time required for accessing is very much small compared to that of vector

为什么是这样?
因为我以为都需要不断的几乎同一时间..

why is the case ? because I thought both takes constant and nearly same time ..

推荐答案

由于大部分(如果不是全部)的std ::矢量使用 T * 阵列内部,不应该有性能差异访问向量元素,并使用 [] 运营商C-数组元素之间的所有在优化参数设置。使用编译器的优化标志再次尝试测试。

Since most (if not all) implementations of std::vector use a T* array internally, there should be no performance difference at all between accessing a vector element and a C-array element using the [] operator when optimization flags are set. Try your test again using your compiler's optimization flags.

不过,这未必是使用的情况下的std ::矢量&lt; T&GT; ::在功能,因为该功能将执行边界检查

However, this may not be the case using the std::vector<T>::at function, since this function will perform a bounds check.

这篇关于在访问数组比访问矢量快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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