使用std :: vector的开销? [英] Overhead to using std::vector?
问题描述
我知道手动动态分配内存通常不是一个好主意,但是有时候它比使用 std :: vector
更好吗?
I know that manual dynamic memory allocation is a bad idea in general, but is it sometimes a better solution than using, say, std::vector
?
举一个简单的例子,如果我必须存储一个 n
整数数组,其中 n
< = 16,例如。我可以使用
To give a crude example, if I had to store an array of n
integers, where n
<= 16, say. I could implement it using
int* data = new int[n]; //assuming n is set beforehand
或使用向量:
std::vector<int> data;
使用 std :: vector绝对是一个更好的主意吗? / code>还是在实际情况下手动分配动态内存会更好,以提高效率?
Is it absolutely always a better idea to use a std::vector
or could there be practical situations where manually allocating the dynamic memory would be a better idea, to increase efficiency?
推荐答案
总是最好使用 std :: vector
/ std :: array
,至少直到可以(通过概要分析)结论性地证明,在特定情况下 T * a = new T [100];
解决方案要快得多。这不太可能发生: vector
/ array
是围绕普通旧数组的极其薄的一层。使用 vector :: at
进行边界检查会有一些开销,但是您可以使用 operator []
来规避。
It is always better to use std::vector
/std::array
, at least until you can conclusively prove (through profiling) that the T* a = new T[100];
solution is considerably faster in your specific situation. This is unlikely to happen: vector
/array
is an extremely thin layer around a plain old array. There is some overhead to bounds checking with vector::at
, but you can circumvent that by using operator[]
.
这篇关于使用std :: vector的开销?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!