C ++,为什么数组比向量更快并且使用更少的内存

C++, Why array is faster and use less memory than vector

在一道 leetcode 题中。 当我使用 std::vector 存储东西时。 i_maxj_max 是整数。

vector<int> left_vec(i_max);
vector<int> right_vec(j_max);

运行时:100 毫秒,内存使用:71.5MB。

当我使用std::array存储东西时。

int left_vec[i_max];
int right_vec[j_max];

运行时:40 毫秒,内存使用:16.1MB。

代码的其他部分完全相同,唯一的区别是使用向量或数组。

我很困惑为什么会这样。

vector分配在堆上,array分配在栈上。

堆分配需要时间。

数组是分配在 stack 上的简单数据序列。

向量是一个可能在 heap. (I am not sure on that one for ALL cases, I think it might depend on the C++ std library implementation and compiler optimization depending on what you are doing with the vector. Two posts on that here and here 上分配的对象。根据经验,认为它是在堆上分配的。

你有一个很好的直觉,即使它不完全“技术上准确”并且与我刚才所说的堆栈和堆无关。

数组非常简单,你给它一个类型和一个大小就够了。您的工作是担心不能访问数组边界之外的值,如何以及在何处保存或访问数组中的值,跟踪数组的大小...

另一方面,矢量是具有许多功能的完整对象。它为您提供了许多方法来帮助您插入、弹出、读取、检查其大小...这是有代价的。