在 C++ 中使用数组或 std::vectors,性能差距是什么?
在我们的 C++ 课程中,他们建议不要再在新项目中使用 C++ 数组.据我所知,Stroustroup 本人建议不要使用数组.但是否存在显着的性能差异?
In our C++ course they suggest not to use C++ arrays on new projects anymore. As far as I know Stroustroup himself suggests not to use arrays. But are there significant performance differences?
推荐答案
应避免将 C++ 数组与 new
一起使用(即使用动态数组).有一个问题是您必须跟踪大小,您需要手动删除它们并进行各种整理.
Using C++ arrays with new
(that is, using dynamic arrays) should be avoided. There is the problem you have to keep track of the size, and you need to delete them manually and do all sort of housekeeping.
也不鼓励在堆栈上使用数组,因为您没有范围检查,并且传递数组会丢失有关其大小的任何信息(数组到指针的转换).在这种情况下,您应该使用 boost::array
,它将 C++ 数组包装在一个小类中,并提供一个 size
函数和迭代器来迭代它.
Using arrays on the stack is also discouraged because you don't have range checking, and passing the array around will lose any information about its size (array to pointer conversion). You should use boost::array
in that case, which wraps a C++ array in a small class and provides a size
function and iterators to iterate over it.
现在是 std::vector 与原生 C++ 数组(取自互联网):
Now the std::vector vs. native C++ arrays (taken from the internet):
// Comparison of assembly code generated for basic indexing, dereferencing,
// and increment operations on vectors and arrays/pointers.
// Assembly code was generated by gcc 4.1.0 invoked with g++ -O3 -S on a
// x86_64-suse-linux machine.
#include <vector>
struct S
{
int padding;
std::vector<int> v;
int * p;
std::vector<int>::iterator i;
};
int pointer_index (S & s) { return s.p[3]; }
// movq 32(%rdi), %rax
// movl 12(%rax), %eax
// ret
int vector_index (S & s) { return s.v[3]; }
// movq 8(%rdi), %rax
// movl 12(%rax), %eax
// ret
// Conclusion: Indexing a vector is the same damn thing as indexing a pointer.
int pointer_deref (S & s) { return *s.p; }
// movq 32(%rdi), %rax
// movl (%rax), %eax
// ret
int iterator_deref (S & s) { return *s.i; }
// movq 40(%rdi), %rax
// movl (%rax), %eax
// ret
// Conclusion: Dereferencing a vector iterator is the same damn thing
// as dereferencing a pointer.
void pointer_increment (S & s) { ++s.p; }
// addq $4, 32(%rdi)
// ret
void iterator_increment (S & s) { ++s.i; }
// addq $4, 40(%rdi)
// ret
// Conclusion: Incrementing a vector iterator is the same damn thing as
// incrementing a pointer.
注意:如果您使用 new
分配数组并分配非类对象(如普通 int
)或没有用户定义构造函数的类 and 你不想让你的元素最初初始化,使用 new
分配的数组可以有性能优势,因为 std::vector
将所有元素初始化为默认值(0 表示int,例如)关于建筑(感谢@bernie 提醒我).
Note: If you allocate arrays with new
and allocate non-class objects (like plain int
) or classes without a user defined constructor and you don't want to have your elements initialized initially, using new
-allocated arrays can have performance advantages because std::vector
initializes all elements to default values (0 for int, for example) on construction (credits to @bernie for reminding me).
相关文章