访问数组比访问向量更快吗?
可能的重复:
在 C++ 中使用数组或 std::vectors,什么是性能差距?
std::vector 比普通数组慢很多?
内存是 1000 个元素的向量 array[] 是一个包含 1000 个元素的整数数组
for (iteration = 0; iteration < numiterations; iteration++) {
for (j = 1; j < numints; j++) {
memory[j] += memory[j - 1];
//array[j] += array[j - 1];
}
}
如果我比较运行 100 次迭代后 for 循环的时间,与向量相比,访问所需的时间非常短,
为什么会这样? 因为我认为两者都需要恒定且几乎相同的时间..
Possible Duplicates:
Using arrays or std::vectors in C++, what's the performance gap?
std::vector is so much slower than plain arrays?
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];
}
}
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 ..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于
std::vector
的大多数(如果不是全部)实现在内部使用T*
数组,因此访问向量元素和访问 C 元素之间应该没有任何性能差异- 设置优化标志时使用[]
运算符的数组元素。使用编译器的优化标志再次尝试测试。但是,使用 std::vector::at 函数时情况可能并非如此,因为该函数将执行边界检查。
Since most (if not all) implementations of
std::vector
use aT*
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.However, this may not be the case using the
std::vector<T>::at
function, since this function will perform a bounds check.这通常(几乎完全)取决于您是否将编译器设置为内联函数。
std::vector
使用一个函数(名为operator[]
)来寻址项目。如果该函数不是内联生成的,则调用该函数的开销将大大增加寻址数组中的项目所需的时间。如果将编译器设置为生成内联函数,则通常无法测量两者之间有意义的差异。This will typically depend (almost entirely) upon whether you've set the compiler to inline functions.
std::vector
uses a function (namedoperator[]
) to address items. If that function isn't generated inline, the overhead of calling the function will add a substantial amount to the time taken to address an item in the array. If you set the compiler to generate inline functions, you normally won't be able to measure a meaningful difference between the two.确实,它们都是常数时间。然而,向量是一个对象,重定向函数调用会受到惩罚。将此视为您第一次体验 C++ 运算符重载。矢量类重载了 [] 运算符以实现与真实数组类似的语义。
True, they both are constant time. However, a vector is an object and there is a penalty for redirecting function calls. Consider this your first experience with C++ operator overloading. The vector class overloads the [] operator to achieve similar semantics with a real array.